Code for displaying the latest posts from the 'recipes' post type..

Home » Snippets » Code for displaying the latest posts from the 'recipes' post type..
0

Created with:

Visibility: 

public

Creator: egbert

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

<?php

namespace WPTurbo;

function wpturbo_display_latest_recipes( $number_of_posts = 5 ) {

    $args = [
        'post_type'      => 'recipes',
        'posts_per_page' => $number_of_posts,
        'post_status'    => 'publish',
    ];

    $latest_recipes = new WP_Query( $args );

    if ( $latest_recipes->have_posts() ) {
        echo '<ul>';

        while ( $latest_recipes->have_posts() ) {
            $latest_recipes->the_post();
            printf(
                '<li><a href="%1$s">%2$s</a></li>',
                esc_url( get_permalink() ),
                esc_html( get_the_title() )
            );
        }

        echo '</ul>';
        wp_reset_postdata();
    } else {
        echo '<p>' . esc_html__( 'No recipes found.', 'wpturbo' ) . '</p>';
    }
}

wpturbo_display_latest_recipes();
				

This code defines a function wpturbo_display_latest_recipes() which queries the latest posts from the 'recipes' post type. The function accepts an optional parameter $number_of_posts, which defaults to 5. Inside the function, we set up a query using WP_Query to fetch the latest recipes.

If there are posts found, it loops through them and outputs each recipe as a list item with a link to the post. If no posts are found, it displays a message indicating that no recipes are available. The function is called at the end to display the latest recipes immediately when the file is executed.

Remember to call this function wherever you want to display the latest recipes in your plugin or theme.

Register an account to save your snippets or go Pro to get more features.