How to list a custom post type inside a Gutenberg blog post

Want to output a custom post type list inside of your Gutenberg blog post? Well here's how!

To achieve this with a custom PHP function and echo, you can create a shortcode that generates the custom post list and then use that shortcode in your Gutenberg blog post.

If you have a child theme or a custom functions plugin, simply copy and paste the snippet below in the functions.php file. Alternatively, if you use a code plugin like WPCodebox, you can create a new PHP snippet in there.

// Function to get the custom post list based on attributes.
function custom_post_list_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'post_type'      => 'your_custom_post_type', // Replace 'your_custom_post_type' with the slug of your custom post type.
        'number'         => 5, // The default is 5 posts.
    ), $atts );

    $args = array(
        'post_type'      => $atts['post_type'],
        'posts_per_page' => $atts['number'],
    );

    $custom_posts = new WP_Query( $args );

    ob_start(); // Start output buffering to capture the HTML.

    if ( $custom_posts->have_posts() ) {
        echo '<ul class="custom-post-list">';
        while ( $custom_posts->have_posts() ) {
            $custom_posts->the_post();
            echo '<li class="custom-post-list__items"><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
    } else {
        echo 'No custom posts found.';
    }

    wp_reset_postdata(); // Restore original post data.

    return ob_get_clean(); // Return the captured HTML as the output of the shortcode.
}
add_shortcode( 'custom_post_list', 'custom_post_list_shortcode' );

Now, you can use the [custom_post_list] shortcode in your Gutenberg blog post to display the custom post list.

Of course if you’d like to style the way it looks with some CSS, you can simply target the classes .custom-post-list and .custom-post-list__item to style as required in your code editor.

Let's talk.

Google reCaptcha: Invalid site key.