List all WordPress Custom Post Types in a Menu

cpt-wordpress-listWant to display a list of a certain WordPress Custom Post Types in a list or menu? You can do this with a simple query using WP Query.

WP Query is the preferred function to query all posts in WordPress and has a multitude of arguments and parameters that can be passed in to change the output.

<?php

// Define the WP query
$args = array(
    'post_type' => 'custom-post-type-name',//Swap in your CPT
    'posts_per_page' => -1,
);

$query = new WP_Query( $args );

if ($query->have_posts()) {

    // Output the post titles in a list
    echo '<ul id="cpt-menu">';

        // Start the Loop
        while ( $query->have_posts() ) : $query->the_post(); ?>

        <li class="cpt-menu-item" id="post-<?php the_ID(); ?>">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>

        <?php endwhile;

        echo '</ul>';
}

// Reset the WP Query
wp_reset_postdata();

?>

In the arguments $args add your defined Custom Post Type name to ‘post_type’. To display all the posts set ‘posts_per_page’ to -1. To see more extensive arguments, they are all listed in the Codex.

You can add in CSS classes to the HTML, defining both the list and list item elements. The code is set to output the post title only which is wrapped in the permalink of that post. If you need to output this in a widget just ensure you have allowed PHP to run in the widgets.

Leave all Comment