简体   繁体   中英

Wordpress Filter Posts by Tags

I am trying to filter posts by tags.

Posts with all tags are available by default. But a user can increase and decrease the number of tags in the filter.

What is the best way to filer post that way? Should I count all omitted tags and work with URL arguments or is there an easier way?

$args  =
        array(
             'tag'        => $tags_arr, //array('sport', 'art', 'news')
         );
$posts_by_tags = get_posts( $args );
foreach ( $posts_by_tags as $post_by_tags ){
  echo '<li>' . $post_by_tags->post_title . '</li>';
}

UPD:

I decided to make links like:

 <ul> <li><a href="?tags=apples,oranges">Bananas</a></li> <li><a href="?tags=bananas,oranges">Apples</a></li> <li><a href="?tags=apples,bananas">Oranges</a></li> </ul>

PHP:

$tags = array();
foreach ( get_tags() as $before_tag ) {
    $tags[] = $before_tag->name;
}
if ( isset( $_REQUEST['tags'] ) && $_REQUEST['tags'] != '' && $_REQUEST['tags'] != null ) {
    $filter_tags = explode( ',', $_REQUEST['tags'] );
} else {
    $filter_tags = $tags;
}
$args =
    array(
        'tag'         => $filter_tags,
    );
$posts_by_tags = get_posts( $args );
$each_sixth    = 1;
foreach ( $posts_by_tags as $post_by_tags ){
    // do stuff
    echo get_the_title( $post_by_tags->ID );
}

Try this,

$query=new WP_Query(array('posts_per_page=-1', array('tag' => array($tags_arr))));

(OR)

$args=array('posts_per_page' => 5, 'tag' => $tags_arr);

$wp_query = new WP_Query( $args );

After loop your posts...

Finally, reset post data:

wp_reset_postdata();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM