Shortcode creation for CPT
Create the shortcode for our custom post type.
Step 1: Add the below code into functions.php
Here custom post type name is ‘events’
add_shortcode( 'all-events', 'display_custom_post_type' );
function display_custom_post_type()
{
$args = array(
'post_type' => 'events',
'post_status' => 'publish'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<ul>';
while( $query->have_posts() ){
$query->the_post();
$string .= '<li>' . get_the_title() . '</li>';
$string .= '<p>' . get_the_excerpt() . '</p>';
}
$string .= '</ul>';
}
wp_reset_postdata();
return $string;
}
Step 2: Add the short code wherever you want to display the events list
[all-events]
Leave a Reply