I've seen several (and have tried at least 15+ methods here on StackExchange) ways of how to do the custom post type loop, none work in my case.
I have tried methods using paged and without, using custom navigation and with resetting the permalinks.
I can get the posts to show, the issue I'm experiencing is with the navigation loading the same content despite the link changing to page-2.
Here is my current method without the use of paged
<?php
$args = array('post_type' => array('posts', 'affiliate-products'));
query_posts($args);
if (have_posts()) : while (have_posts()) : the_post();
get_template_part('template-parts/content', 'product');
endwhile;
the_posts_navigation();
else :
?>
<p><?php esc_html_e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
Could anyone please suggest a way of doing this with working pagination for front-page.php? Thanks in advance! <3
EDIT:
Current non-working code, based on the suggestions regarding the 'pre_get_posts' function:
Homepage loop
<?php
if (have_posts()) : while (have_posts()) : the_post();
get_template_part('template-parts/content', 'product');
endwhile;
the_posts_navigation();
else :
?>
<p><?php esc_html_e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
functions.php
add_action( 'pre_get_posts', function( \WP_Query $query) {
if ( is_home() && $query->is_main_query() ) {
$query->set('post_type', 'affiliate-products');
$query->set( 'posts_per_page', 3 );
}
} );
any ideas? :)
query_posts
has a significant number of disadvantages, it doesn't change the posts that WP gives you, instead it throws away the posts and performs a second query. There are far better ways to modify which posts WP fetches than this to include custom post types on a page. By usingquery_posts
you've doubled the number of queries, and have to re-implement all the functionality from scratch, e.g. pagination, it's the worst case scenario by default