1

First of all thanks for your time!

Im trying to show only the last element of my Custom post type (CPT) in the archive page, I tried it but it is showing the las Post, not the last CPT element, I dont know what im doing wrong but I think is this line:

<?php $the_query = new WP_Query('showposts=1'); ?>

here you can see my code.

Would you be able to help me? Thanks in advance.

https://github.com/cmr96/WordPress/blob/master/archive-cpt_proyectos.php

0

Please thoroughly read the WP_Query docs, especially that part about post types. Means you need to pass the query the post type you want to query:

$args = array(
    'post_type'      => 'my_custom_post_type',
    'posts_per_page' => 1,
);
$query = new WP_Query( $args );

Even better it would be to simply override the existing query for that archive page by hooking into pre_get_posts. This will for example also adjust the pagination accordingly. Place this in your functions.php:

/**
 * Override the main query on a custom post type archive.
 *
 * @param \WP_Query $wp_query
 */
function wpse_337567( WP_Query $wp_query ) {

    // Only check this on the main query.
    if ( $wp_query->is_main_query() && is_post_type_archive( 'my_custom_post_type' ) && !is_admin() ) {
        $query->set( 'posts_per_page', 1 );
    }
}
add_action( 'pre_get_posts', 'wpse_337567' );

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.