Support » Themes and Templates » Getting tags with WP_Query

Getting tags with WP_Query

  • Hello again

    I can’t find a way to make my tags appear when I use WP_Query to display my posts.

    <?php $cat_posts = new WP_Query('cat=-5&orderby=post_date&posts_per_page=1'); ?>
    <?php if($cat_posts->have_posts()) : ?><?php while($cat_posts->have_posts()) : $cat_posts->the_post(); ?>
    <div class="post" id="post-<?php the_ID(); ?>">
    	<h1><?php the_title(); ?></h1>
    	<h3>Wrote post in: <?php the_tags('', ', ', ''); ?> </h3>
    		$content = ob_get_clean();
    		echo $content;
    <?php endwhile; ?>
    <?php endif; ?>

    I found out that the_tags returns an array, but what to do with that to make it display?

Viewing 3 replies - 1 through 3 (of 3 total)
  • you should be able to use

    <?php the_tags('Wrote post in:' ', ' ''); ?>

    as shown in the examples on this page

    Thanks for the reply, but I tried that and it didn’t show anything.

    If I use
    <?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>
    and then
    <?php the_tags('Wrote post in:' ', ' ''); ?>

    it works, but with that WP_Query, it doesn’t show 🙁


    with get_posts() you can use setup_postdata() just after the loop starts to get access to certain functions otherwise not available within a get_posts loop

    get_posts is very similar to a WP_Query loop. I’ve not tried setup_postdata() with a WP_Query loop but it would be worth trying

    Some post-related data is not available to get_posts by default, such as post content through the_content(), or the numeric ID. This is resolved by calling an internal function setup_postdata(), with the $post array as its argument:

     $lastposts = get_posts('numberposts=3');
     foreach($lastposts as $post) :
     <h2><a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>"><?php the_title(); ?></a></h2>
     <?php the_content(); ?>
     <?php endforeach; ?>

    To access a post’s ID or content without calling setup_postdata(), or in fact any post-specific data (data retained in the posts table), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. To display or print this data on your page use the PHP echo command, like so:

    <?php echo $post->ID; ?>

    from http://codex.wordpress.org/Template_Tags/get_posts

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Getting tags with WP_Query’ is closed to new replies.
Skip to toolbar