1

I'm building a child theme and have set up an additional custom post type ('blogs').

I need regular and custom posts to be returned on the archive page. The have_posts function only returns regular posts.

How do I amend the have_posts function to include custom posts?

<?php if ( have_posts() ) : 
    while ( have_posts() ) :
        the_post();
    endwhile;  wp_reset_postdata();
endif;
?>

I did try this approach:

<?php
$args = array(
    'post_type' => array( 'post', 'blogs' ),
);  
$myQuery = new WP_Query($args);
    
if ($myQuery->have_posts() ) : 
    while ($myQuery->have_posts() ) :
    $myQuery->the_post();
    endwhile;  wp_reset_postdata();
endif;
?>

Which returned posts and 'blogs' - but from ALL categories, instead of posts and 'blogs' with the relevant category.

Any advice would be much appreciated as I'm new to Wordpress dev.

4
  • 2
    have_posts doesn't perform the query, take a look at the pre_get_posts filter – Tom J Nowell Mar 8 at 18:09
  • Can you make it clear that which relevant category are you referring? Post type and categories are different things in WordPress. – Ashok Dhaudk Mar 8 at 20:45
  • Hi - I mentioned categories because I want the archive page to show both types of posts - when a link to a Category is clicked. – user1953359 Mar 9 at 12:06
  • Thanks to Tom for suggesting the pre_get_posts hook. this partially solved the issue: wpshout.com/practical-uses-pre_get_posts ``` function display_custom_posts_on_archives( $query ) { if( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'blogs' ) ); } } add_action( 'pre_get_posts', 'display_custom_posts_on_archives' ); ``` However, now my custom post archive page and the custom post backend now shows ALL posts rather than just custom posts. – user1953359 Mar 9 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.