WordPress Shortcode that displays posts (Custom Query)

What is a Custom Query Shortcode?

A custom query shortcode is a piece of code that you can insert into your WordPress post or page that executes a custom query to the WordPress database. It retrieves content dynamically according to your specifications. This means you can create lists of posts, products, or any custom content without directly editing templates or writing complex PHP code each time.

Use Cases for a Custom Query Shortcode

  • Display a list of the latest posts within a particular category or tag.
  • Showcase featured products in a specific order.
  • List upcoming events or recent portfolio projects.

Creating Your Custom Query Shortcode

Step 1: Define the Shortcode Function

First, we’ll create a new function in our functions.php file that defines what our shortcode does. This function will use the WP_Query class to fetch posts according to the attributes we specify.

function custom_query_shortcode($atts) {
        'posts_per_page' => 5,
        'category_name' => '', // Use the category slug
    ), $atts));

    $query_args = array(
        'posts_per_page' => intval($posts_per_page),
        'category_name'  => $category_name,
    $query = new WP_Query($query_args);

    if ($query->have_posts()) : 
        echo '<ul>';
        while ($query->have_posts()) : $query->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        echo '</ul>';
    return ob_get_clean();

Step 2: Register the Shortcode

Below our function, we need to add a line to tell WordPress to create a shortcode [custom_query] that will trigger our function.

add_shortcode('custom_query', 'custom_query_shortcode');

Step 3: Usage

Now, anywhere in your posts or pages, you can use the shortcode [custom_query] to display the content. For example:

  • [custom_query posts_per_page="10" category_name="news"] would display the 10 most recent posts from the “news” category.

Customizing Your Query

The beauty of this shortcode is that it’s highly customizable. You can add more attributes to filter by tag, date, custom post type, and more. Modify the $query_args array to include any parameters supported by WP_Query.