I’m new to loop customisation and I have an issue getting my search page front end filter loop working in the same way as my other category template post loop.
This is the loop I am using for the category templates which works fine.
<?php $custom_query_args = array( 'cat' => '2', 'posts_per_page' => 6 );
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$custom_query = new WP_Query( $custom_query_args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
if ( $custom_query->have_posts() ) :
while ( $custom_query->have_posts() ) :
$custom_query->the_post(); ?>
This allows me to paginate through all posts in this category but I need to convert a similar code block on my search page to allow it to do the same, currently the search template code below doesn’t paginate like the above.
<?php wp_reset_postdata();
global $wp_query;
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
foreach($_POST['filter_cat'] as $fcat){$fcat_list .= $fcat . ",";}
query_posts(
array_merge(
array(
'cat' => $fcat_list,
'posts_per_page' => 6,
'paged' => $paged
),
$wp_query->query
)
); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
I know that the first code block is a better method but I can’t figure out how to use the second block in the same way.
Edit:
Ok please excuse my inexperience.
Thanks to Pieter Goosen I’m part way there with using pre_get_posts.
I’ve done so successfully with category template but using the following for the search page template kills the site, I’m not sure where I’m going wrong.
function paginate_search ( $query ) {
if( $query->!is_admin() ) {
foreach($_POST['filter_cat'] as $fcat){$fcat_list .= $fcat . ",";}
query_posts( array_merge ( array (
'cat' => $fcat_list,
'posts_per_page' => 6,
'paged' => $paged
),
$wp_query->query
) ); } }
add_action( 'pre_get_posts', 'paginate_search' );