0

I have registered a custom post type and inside my archive-myCPT.php I want to retrieve just the current published post.

Here is a relevant snippet from my archive-myCPT.php:

<?php 

    if( have_posts() ){
        $x = 1;
        while ( have_posts() ){
            the_post(); 
            if ( 0 === (int) $post->post_parent ) {
                get_template_part( 'inc/post-format/content-debate');
            }

I've tried adding this : query_posts('posts_per_page=1&order=DESC&orderby=date') before the if( have_posts() ){ but I'm getting the last post from the default blog posts not from my CPT and also it adds also a pagination.

How can I retrieve just the most recent published post inside my CPT without the pagination?

1 Answer 1

3

You could just alter the main query for your custom post type archive with pre_get_posts().

Code:

function wpse124228_alter_ppp_order_for_mycpt( $query ) {
    if ( ! $query->is_main_query() || is_admin() )
        return;
    if ( is_post_type_archive( 'mycpt' ) ) {
        //Only display 1 post on mycpt archive
        $query->set( 'posts_per_page', 1 );
        //Most recent/current
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
}
add_action( 'pre_get_posts', 'wpse124228_alter_ppp_order_for_mycpt' );

This pretty much resembles this example from the codex page. BTW don't use query_posts(), if you have to do a second query go with WP_Query, but for an archive that shouldn't be necessary.

Additional Information:

5
  • What about if I have to retrieve also inside my archive-CPT.php the most recent post with the status of future and the last published post ?
    – agis
    Nov 24, 2013 at 21:46
  • This would be a totally different question. BTW how can a future post be most recent, I guess you mean the next to come. But this really should be a new question, because it's a new problem. @Alecs Nov 24, 2013 at 22:32
  • Sorry, I meant the next to come ...
    – agis
    Nov 25, 2013 at 11:42
  • I've added a question regardin this here
    – agis
    Nov 25, 2013 at 11:43
  • Not a problem, can you check mark the answer to resolve the process. I'll take a look at your other question. @Alecs Nov 25, 2013 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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