levandesigns
Member
Posted 2 years ago #
Hey all,
So I'm trying to list the tags attached to a post when viewed as a single page. This is all well and fine if I place the_tags() in the loop, however, is there a way to display the current post's tags in the sidebar? Things like the_title() seem to work fine outside of a loop, but the_tags and others don't seem to have any output when used in the sidebar
Tim-dpi
Member
Posted 2 years ago #
Hi,
I want something similar to this. I want the all tags available in the post on my archive.php to be shown in the sidebar. How can I do this?
john.andrews
Member
Posted 2 years ago #
Here's just one example. In your sidebar.php define the post id as a global variable and call a custom function from functions.php
sidebar.php
// define globals
global $constant_post_id;
$constant_post_id = $post->ID;
// get post tags
get_content(sidebar_post_tags);
functions.php
function get_content($element) {
do_action($element);
};
function get_sidebar_post_tags() {
global $constant_post_id;
$content .= "<h2>Tags<h2><ul>";
$tags = wp_get_object_terms($constant_post_id, 'post_tag');
foreach ($tags as $tag) {
$content .= "<li><a href=\"".get_tag_link($tag->term_id)."\">$tag->name</a></li>";
};
$content .= "</ul>";
echo $content;
}
add_action('sidebar_post_tags','get_sidebar_post_tags');
Thanks for the code, I made a few edits so I could use it to pull in the post tags for meta keywords. I had 2 questions, is there a better way to do this? and how can I get rid of the last comma?
Here is the code...
function get_content($element) {
do_action($element);
};
function get_post_tags() {
global $constant_post_id;
$tags = wp_get_object_terms($constant_post_id, 'post_tag');
foreach ($tags as $tag) {
$content .= $tag->name . ",";
};
echo $content;
}
add_action('post_tags','get_post_tags');
john.andrews
Member
Posted 2 years ago #
Answer to your first question. Insert this before echo $content.
$content = rtrim($content,',');
As for your second question. I'm sure there is 1000 different ways to do the same thing. If this works for you, then go with it.