Conditional Check if Custom Post Type Posts Are Published

You can check on the existence of published Custom Post Types by using a new WP_Query loop with an if/else statement, as the CPT is already registered it is difficult to use a conditional check without checking the loop of posts.

add_filter('wp_nav_menu_primary-menu_items', 'wpb_add_menu_item', 10, 2);
// Add to primary menu based on CPT existence
function wpb_add_menu_item( $items, $args ) {
    global $post;
    // Arguments, adjust as needed
    $args = array(
        'post_type' => 'job', // Swap to your CPT

    // Use $loop, a custom variable we made up, so it doesn't overwrite anything
    $loop = new WP_Query( $args );

    if ( $loop->have_posts() ) : // Test if any CPT posts exist

        // If CPT posts exist do this
        $items .= '<li class="menu-item menu-item-type-post_type menu-item-object-page">
                    <a href="/jobs">Jobs</a></li>';
        return $items;
        // If CPT posts don't exist do this
        return $items; 


So this example is using a filter that adds items to the menu, but I only want to add the menu item if a certain CPT has posts published.

A new WP_Query loop is created and assigned to a CPT, the loop is run and if the posts exist then the menu item is added otherwise the default content is returned. Reset the loop at the end of the function.

The same logic can be applied to any filter or action.

Leave all Comment