[wp-hackers] Help with including custom templates using variables

J.D. Grimes jdg at codesymphony.co
Mon Aug 12 13:02:48 UTC 2013

Hi Greg,

wp_get_post_tags() returns an array of tags for the post. By default, each of the tags in the array is represented by the tag object (see https://codex.wordpress.org/Function_Reference/wp_get_post_tags#Examples). But you don't need the whole object for each tag, only the tag name. You can change the behavior of wp_get_post_tags() to return only the tag names using the $args parameter like this:

$args = array( 'fields' => 'names' );
$tag_names = wp_get_post_tags( $post->ID, $args );

$tag_names will now contain an array of the names of the tags for the post. If you just want to load the sidebar based on the first tag, then you could do this:

$tag = $tag_names[0];
$file = "left-sidebar-$tag";

If your posts will have several tags, then you may need to do something more sophisticated instead to determine which tag takes precedence for sidebar loading.

I hope that helps.


On Aug 12, 2013, at 2:05 AM, Gregory Lancaster <greglancaster71 at gmail.com> wrote:

> I have a theme that I would like to include unique left-sidebar for some
> posts.  The custom sidebar templates are formatted like
> "left-sidebar-$tag", $tag being the taged posts I want this sidebar to show
> up on.
> How can I append the tag name using wp_get_post_tags to the end of the file
> name?  I tried calling it within the string, no success.  I am still
> learning php so if this is obvious I apologize - but any help would be
> greatly appreciated!
> Greg
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers

More information about the wp-hackers mailing list