0

I want to get several post by tag. So I try to use get_posts() function:

<?php $args = array(
    'numberposts' => '3',
    'post_status' => 'publish',
    'tag' => 'travel'
);

$recent_posts = get_posts($args);?>

But it doesn't work. How can I get posts by tag?

2 Answers 2

1

Look at this section: Tag parameters in WP Codex, where is explained search by tags.

Your code like right. Try change numberposts to int:

<?php $args = array(
    'numberposts' => 3,
    'post_status' => 'publish',
    'tag' => 'travel'
);
0

You may find it helpful to check out this link about WP Queries to query by tag.

The advantage of using this query is you can create your own loop, and you can put the posts in whatever arrangement you need.

For example, you can drop the post titles into a list, or you can generate the standard title headings followed by an excerpt or content.

For a list, the code would look something like this:

<ol>

  <?php $args = array(
  'tag' => 'travel', 
  'posts_per_page' => 3); ?>

  <?php $recent_posts = new WP_Query( $args ); ?>

  <?php if ($recent_posts->have_posts()) : 
        while ($recent_posts->have_posts()) : $recent_posts->the_post();
   ?>


    <li><?php the_title(); ?></li>

  <?php endwhile; 

     else :
     echo "Nothing";
      endif;
      wp_reset_postdata();
  ?>
</ol>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.