Ty T.
Ty T.

Reputation: 586

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.

Upvotes: 2

Views: 1674

Answers (2)

Tim Sheehan
Tim Sheehan

Reputation: 4024

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.

Upvotes: 5

David
David

Reputation: 5937

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();

Upvotes: 0

Related Questions