What I want to achieve

I have a custom page template, and I'd like to display some selected Posts on that Page. I'm developing this feature with shortcode. For now, I only need to receive the post ids in the page template.

What I have tried

In functions.php:

function post_link_shortcode($atts) {
    $atts = shortcode_atts(
            'id' => '',
add_shortcode('featured_posts', 'post_link_shortcode');

In the admin panel page editor I have added:

Here are the featured posts: [featured_posts id="358,328"]

In the page template:

echo do_shortcode("[featured_posts]");

What I expect

It outputs Here are the featured posts: 358,328 on the page along with the normal content. But It doesn't. Any ideas?


You can't just stick a shortcode somewhere and expect it to do something. It's basically an buffer that will take whatever code it's told to generate, compile it exactly how you tell it to, and then output it wherever the shortcode is placed.

Take a look at the Shortcode API for more information.

As for your specific example, you don't actually have anything in your shortcode that says "do something with posts 358 and 328".

You'll need to make use of something like WP_Query() or get_posts() inside your shortcode. You may also consider using a more unique name for your function and shortcode than post_link_shortcode and featured_posts to avoid naming conflicts.

Take this for example:

add_shortcode( 'stickers_featured_posts', 'stickers_featured_posts_function');
function stickers_featured_posts_function( $atts ){
    extract( shortcode_atts( array(
        'ids'   => '',
    ), $atts ) );

    // Remove whitespace from IDs
    // ex: '123, 321' => '123,321'
    $ids = preg_replace('/\s+/', '', $ids);

    // Turn string of ID's into array
    // ex: '123,321' => array(123, 321);
    $id_array = explode( ',', $ids );

    $args = array(
        'post__in' => $id_array

    $featured_query = new WP_Query( $args );
    if( $featured_query->have_posts() ){
        echo '<ul>';
        while( $featured_query->have_posts() ){
        echo '</ul>';
    } else {
        echo 'Post IDs not found';

And the usage would be like [stickers_featured_posts ids="123,321"] - The final output would be whatever you put in the while loop, in the case about - a simple list of post titles.

Your Answer

