WordPress Query by Tag(Priority) then Category(backfill)

I’ve search high and low but have been unable to find a solution to my problem. Hopefully this isn’t a duplicate question that I was unable to find through search here and on google.

I’m attempting to have a wp_query return a set number of results (10) that are populated by any posts found in the current pages category. I was able to accomplish this with…

Read More
$postCategories = get_the_category();

$atts = array ( 
    'posts_per_page' => 10,
    'tag' => 'sticky',
    'category_name' => $postCategories[0]->slug,
);

But where I’m having trouble is with the tag. I would like any posts that have the tag ‘sticky’ to take priority over any of the posts being brought in by the category match while not adding any more than 10 results still.

Any help or guidance would be much appreciated as i’m kind of a newbie to php. Thanks

Related posts

1 comment

  1. I think this could work for you, but it’s hard to know for sure without knowing the specifics of your project.

    <ul>
        <?php $sticky = get_option( 'sticky_posts' ); // Get sticky posts ?>
        <?php $args_sticky = array(
            'post__in'  => $sticky,
            'posts_per_page' => 10, // Limit to 10 posts
            'ignore_sticky_posts' => 1
        ); ?>
        <?php $sticky_query = new WP_Query( $args_sticky ); ?>
        <?php $sticky_count = count($sticky); // Set variable to the number of sticky posts found ?>
        <?php $remaining_posts = 10 - count($sticky); // Determine how many more non-sticky posts you should retrieve ?>
        <?php if ($sticky_count > 0) : // If there are any sticky posts display them ?>
            <?php while ( $sticky_query->have_posts() ) : $sticky_query->the_post(); ?>
                <li><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a></li>
            <?php endwhile; ?>
        <?php endif; ?>
    
        <?php wp_reset_query();  // Restore global post data ?>
    
        <?php if ($remaining_posts > 0) : // If there are non-sticky posts to be displayed loop through them ?>
            <?php $postCategories = get_the_category(); ?>
            <?php $loop = new WP_Query( array( 'post_type' => 'post', 
                'posts_per_page' => $remaining_posts,
                'post__not_in' => get_option( 'sticky_posts' ),
                'category_name' => $postCategories[0]->slug
            ) ); ?>
            <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
                <li><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a></li>
            <?php endwhile; ?>
            <?php wp_reset_query();  // Restore global post data ?>
        <?php endif; ?>
    </ul>
    

Comments are closed.