wordpress get custom post type posts code example
Example 1: wp_query get custom post type
<?php
$args = array(
'post_type' => 'custom_type',
'post_status' => 'publish',
'posts_per_page' => 8,
'orderby' => 'title',
'order' => 'ASC',
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
print the_title();
the_excerpt();
endwhile;
wp_reset_postdata();
?>
Example 2: query custom post type
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) {
$loop->the_post();
?>
<div class="entry-content">
<?php the_title(); ?>
<?php the_content(); ?>
</div>
<?php
}
Example 3: get name custom post type wordpress
$pt = get_post_type_object( 'books' );
echo $pt->label;
echo $pt->labels->name;
echo $pt->labels->singular_name;
Example 4: wordpress get 10 posts of each custom post type
function delete_front_page_query_results() {
delete_transient('post_data');
$query_cpt1 = array (
'posts_per_page' => 3,
'post_type' => 'cpt1'
);
$query_cpt2 = array (
'posts_per_page' => 3,
'post_type' => 'cpt2'
);
$query_cpt3 = array (
'posts_per_page' => 3,
'post_type' => 'cpt3'
);
$query_cpt4 = array (
'posts_per_page' => 3,
'post_type' => 'cpt4'
);
$query_cpt5 = array (
'posts_per_page' => 3,
'post_type' => 'cpt5'
);
$query_results[] = get_posts($query_cpt1);
$query_results[] = get_posts($query_cpt2);
$query_results[] = get_posts($query_cpt3);
$query_results[] = get_posts($query_cpt4);
$query_results[] = get_posts($query_cpt5);
$flatten_array =array();
foreach ($query_results as $data) {
foreach($data as $flatten_data) {
$flatten_array[] = $flatten_data;
}
}
function cpt_array_sort($a, $b) {
return strtotime($b->post_date) - strtotime($a->post_date);
}
usort($flatten_array, 'cpt_array_sort');
set_transient ( 'post_data', $flatten_array, 365*24*60*60);
}
add_action('publish_post', 'delete_front_page_query_results);