Wordpress: trying to get posts by tag

前端 未结 3 1196
忘了有多久
忘了有多久 2020-12-10 02:42

I\'ve written some code which automatically creates some posts and adds a tag to them. I can see the tags in the \'All posts\' admin panel and I can click on the posts \'Ta

相关标签:
3条回答
  • 2020-12-10 03:19

    Try this

    $original_query = $wp_query;
    $wp_query = null;
    $args=array('posts_per_page'=>5, 'tag' => $brand_name);
    $wp_query = new WP_Query( $args );
    if ( have_posts() ) :
        while (have_posts()) : the_post();
            echo '<li>';
            the_title();
            echo '</li>';
        endwhile;
    endif;
    $wp_query = null;
    $wp_query = $original_query;
    wp_reset_postdata();
    
    0 讨论(0)
  • 2020-12-10 03:36

    In your code, try:

    $query=new WP_Query(array('posts_per_page=5', 'tag' => $brand_name));
    

    instead of:

    $query=new WP_Query(array('posts_per_page=5', array('tag' => array($brand_name))));
    

    For further details, see https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters (and as mentioned on a recent duplicate post).

    Note: $brand_name could be an array of strings, or comma separated values, etc., and the above code should work.

    Alternatively, try:

    $myPosts = get_posts(array('tag' => $brand_name));
    

    See https://codex.wordpress.org/Template_Tags/get_posts

    0 讨论(0)
  • 2020-12-10 03:41

    Answer was found here - https://codex.wordpress.org/Template_Tags/get_posts

    Following example displays posts tagged with 'jazz', under 'genre' custom taxonomy, using 'tax_query'

    $args = array(
        'tax_query' => array(
            array(
                'taxonomy' => 'genre',
                'field' => 'slug',
                'terms' => 'jazz'
            )
        )
    );
    $postslist = get_posts( $args );
    

    So for you it will be

    $args = array( 
            'posts_per_page' => 5,
            'tax_query'      => array(
                array(
                    'taxonomy'  => 'post_tag',
                    'field'     => 'slug',
                    'terms'     => sanitize_title( $brand_name )
                )
            )
        );
    
    $postslist = get_posts( $args );
    
    0 讨论(0)
提交回复
热议问题