How to display post type content with shortcode in WordPress?
We can use Shortcode API for creating WordPress shortcodes for use in posts and pages. The add_shortcode
function is used to register a shortcode handler. It takes two parameters: the shortcode name (the string used in a post body), and the callback function name. The API call to register the shortcode handler would look something like this:
add_shortcode( 'myshortcode', 'my_shortcode_handler' );
//Example of shortcode in custom post type
<?php
function portfolio_dropdown_list($atts){
$args = array(
'posts_per_page' => -1,
'post_type' => 'portfolio', // This is the CPT's slug!
'order' => 'ASC',
'orderby' => 'menu_order'
);
$my_query = new WP_Query( $args );?>
<select name="portfolio-filter" class="form-control">
<option >All</option >
<?php
if($my_query->have_posts()):
while($my_query->have_posts()): $my_query->the_post(); ?>
<option > <?php the_title(); ?> </option>
<?php endwhile; // End while $my_query->have_posts
endif; // End if $my_query->have_posts
?>
</select>
<?php
wp_reset_postdata();
}
add_shortcode('portfolio_filter','portfolio_dropdown_list');
Now insert this shortcode [portfolio_filter] in editor or shortcode widget for display the post type content.