sinanisler logo

custom shortcode for query_post loop

The custom_post_type_shortcode function defines a WordPress shortcode that fetches and displays a list of posts from a specified post type. By default, it fetches the latest five entries from the “post” post type. Users can override these defaults by passing attributes to the shortcode. The function first extracts these attributes, then constructs a query to fetch the desired posts. It then initiates a loop to output each post as a list item inside an unordered list. If no posts are found, it outputs a message indicating so. After the loop completes, the query is reset to its original state to prevent conflicts with other loops. Finally, outside of the function, the shortcode is registered with WordPress using add_shortcode, allowing users to add [custom_post_list] in their posts or pages to use this functionality

 

To use this shortcode, you would insert [custom_post_list] into your WordPress content where you want the list of custom posts to appear. You can also customize the display by providing attributes like [custom_post_list type=”post_type” count=”10″]

 

function custom_post_type_shortcode($atts) {
    // Extracting the shortcode attributes, if there are any
    $a = shortcode_atts(array(
        'type' => 'post', // Default post type is "post"
        'count' => 5,     // Default number of posts is 5
    ), $atts );

    // The output string we will return
    $output = "";

    // The Query
    query_posts( array(
        'post_type'      => $a['type'],  // Using the custom post type "post"
        'posts_per_page' => $a['count']
    ));

    // The Loop
    if ( have_posts() ) {
        $output .= '<ul>';
        while ( have_posts() ) {
            the_post();
            $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        $output .= '</ul>';
    } else {
        $output .= 'No posts found';
    }

    // Reset Query
    wp_reset_query();

    return $output;
}

// Register the shortcode
add_shortcode('custom_post_list', 'custom_post_type_shortcode');

 

Leave the first comment