Get post object in shortcode function

I have to display a post from another page (index.php), so my code is

$section_id = 16;
$section_home = get_post($section_id);

setup_postdata( $section_home ); 
the_content();

This post (with ID 16) has a few shortcodes inside. I can’t access the $post object inside of the shortcode functions, for example I tried

Read More
function tp_sc_flipcoin($atts,$content = null){
    global $post;
    var_dump($post);
    return "";
}

add_shortcode( 'tp_flipcoin', 'tp_sc_flipcoin' );

and it displays the post with ID=1, I also tried:

function tp_sc_flipcoin($atts,$content = null){
    var_dump($post);
    return "";
}

add_shortcode( 'tp_flipcoin', 'tp_sc_flipcoin' );

and in this case it displays NULL.

What am I doing wrong?

Related posts

1 comment

  1. You need to reassign the $post yourself. See the WordPress Codex that setup_postdata won’t do it for you. Try this:

    global $post;
    
    $section_id = 16;
    $post = get_post( $section_id );
    setup_postdata( $post ); 
    
    the_content();
    

Comments are closed.