I need to display the IDs of the tags for a post. I've tried
$myTopics_id = '';
$tags = get_the_tags();
foreach($tags as $tag) {
$myTopics_id .= $tag->tag_ID;
}
inside the loop to get the tags to be displayed here:
<div onclick="location.href='<?php the_permalink(); ?>'" data-topics="<?php echo $myTopics_id; ?>">
but it doesn't display anything, the string simply stays empty:
<div onclick="http://localhost/posts/" data-topics="">
What am I doing wrong here?
EDIT: thanks to User biesior, I have changed my code to this now:
<?php $wpb_all_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=>-1)); ?>
<?php if ( $wpb_all_query->have_posts() ) : ?>
<?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post();
/* Get Category ID */
$categories = get_the_category();
$mySection_id = $categories[0]->cat_ID;
/* ------- */
/* Get Tag IDs */
$myTopics_id = '';
$tags = get_tags();
foreach($tags as $tag) {
$myTopics_id .= $tag->term_id;
$myTopics_id .= ", ";
}
?>
<div data-topics="<?php echo $myTopics_id; ?>" data-section="<?php echo $mySection_id; ?>">
... content to be displayed ...
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
but the result is still wrong, as it is adding up the term_ids instead of displaying it individually per post.
So, as an example, my current result is
<div data-topics="15, 16, 13, 12, 10, 8, 11, " data-section="3"> ... </div>
As you can see, the current category per post is being displayed correct. But data-topics value is wrong and the same on every single post. It is possible that there is more than one tag per post. So it would be correct if the result would be let's say
<div data-topics="15, 16, " data-section="3"> ... </div>
for the first post, then
<div data-topics="13, " data-section="7"> ... </div>
for the second
<div data-topics="12, 10, 8, " data-section="1"> ... </div>
for the third post and so on and so on.
But currently every post has the same values for data-topics ("15, 16, 13, 12, 10, 8, 11, "), so there seems to be an error in the loop or in the tag request. But I have no idea WHAT and WHERE.
I'll post my solution here just in case someone arrives with the same problem:
$myTopics = get_the_tags();
$myTopics_id = "";
$myTopics_array = [];
if ($myTopics) {
foreach($myTopics as $tag) {
$myTopics_array[] = $tag->term_id;
}
}
$myTopics_id = implode(',', $myTopics_array);
echo "<div data-topics='{$myTopics_id}'>";