0

I know this has been covered in different ways a thousand times (I read all the posts), but it seems not specifically for my case. I can't really get it to work myself, being a big development noobie.

I have a template which shows the last posts on the front page. I changed the type of posts shown to question (my website is a Q&A one) but then pagination was only showing 13 pages while there are 29 pages of questions. 13 pages being the number of non-custom-type normal posts. So I added this code in functions.php:

add_action( 'pre_get_posts', function($q) { 
    if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) { 
        $q->set ('post_type', array( 'question' ) ); 
    } 
});

Now it counts the number of Questions correctly but it throws a 404 error every time I click on the link to a question. I understand that pre_get_posts is not the best approach, but I really don't know how to change it and use WP_Query instead, as I saw was advised to.

Any fix to that ? Thank you <3

0

This might be a quick fix for your custom post type 404 error page.

Navigate to Settings > Permalinks, and then click the Save Changes button.

Then comeback to check if the links doesn't give you a 404 error.

  • Already tried that, doesn't change anything but ty :) – Lisa Lucas Jul 3 '17 at 21:15
0

If it's the front page query, then you should check for that case instead of !$q->is_tax(), which will be true in lots of cases other than the front page.

add_action( 'pre_get_posts', function($q) { 
    if( !is_admin() && $q->is_main_query() && $q->is_front_page() ) {
        $q->set ('post_type', array( 'articles' ) ); 
    } 
});

and pre_get_posts is indeed the correct way to handle this sort of thing, running an additional query with WP_Query would just waste server resources.

  • Thanks really a lot Milo !! I actually changed it to : add_action( 'pre_get_posts', function($q) { if( !is_admin() && $q->is_main_query() && !$q->is_tax() && $q->is_front_page() ) { $q->set ('post_type', array( 'question' ) ); } }); And now it works both for pagination and single CPT :D :D – Lisa Lucas Jul 5 '17 at 10:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.