wp-query category and has tag

I am trying to query posts in wordpress using wp_query. I would like to place the posts in a category and query by using has_tag. I tried to use

$args = array (
                    'post_type'  => array( 'post' ),
                    'category_name' => 'footer',
                );
                // The Query
                $social = new WP_Query( $args );
                // The Loop
                if ( $social->have_posts()&&has_tag('social') ) {
                    while ( $social->have_posts() ) {
                        $social->the_post();
                        the_content();
                    }
                } rewind_posts();
                ?>

but this loads all of the posts and doesn’t just show the one with the tag.

Related posts

2 comments

  1. The correct way to do this would be limit the WP_Query itself.

    E.g.

    $args = array(
        'post_type'  => array( 'post' ),
        'category_name' => 'footer',
        'tag' => 'social'
    );
    
    $social = new WP_Query( $args );
    
    if ( $social->have_posts() ) {
        while ( $social->have_posts() ) {
            $social->the_post();
            the_content();
        }
    }
    
    wp_reset_postdata();
    

    To use has_tag you’d need to set your global post data up first, e.g. setup_postdata( $social ), which would create a lot of overhead with conditions and loops just to filter your results down when you could do it within the query itself.

  2. you need to check within each post called rather than at the start (note you might need to pass in the 2nd arg of has_tag, the post object.

    if ( $social->have_posts() ) {
                    while ( $social->have_posts() ) {
                        $social->the_post();
                        if( has_tag('social') { 
                            the_content();
                        }
                    }
    } rewind_posts();
    

Comments are closed.