WordPress.org

Ready to get started?Download WordPress

Forums

Getting tags with WP_Query (4 posts)

  1. Jellelle
    Member
    Posted 5 years ago #

    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>
    	<?php
    		ob_start();
    		the_content();
    		$content = ob_get_clean();
    		echo $content;
    	 ?>
    </div>
    
    <?php endwhile; ?>
    
    <?php endif; ?>

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

  2. yeyejoijoi
    Member
    Posted 5 years ago #

    you should be able to use

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

    as shown in the examples on this page
    http://codex.wordpress.org/Template_Tags/the_tags

  3. Jellelle
    Member
    Posted 5 years ago #

    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 :(

  4. stvwlf
    Member
    Posted 5 years ago #

    Hi

    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:

    <?php
     $lastposts = get_posts('numberposts=3');
     foreach($lastposts as $post) :
        setup_postdata($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

Topic Closed

This topic has been closed to new replies.

About this Topic