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.
.php
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/cmr96/WordPress/blob/master/archive-cpt_proyectos.php
Share Improve this question edited May 10, 2019 at 10:22 norman.lol 3,2413 gold badges30 silver badges35 bronze badges asked May 10, 2019 at 7:06 Carlos Martínez RomeroCarlos Martínez Romero 256 bronze badges 3 |1 Answer
Reset to default 0Please 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' );
pre_get_posts
filter. – Jacob Peattie Commented May 10, 2019 at 7:27