First up, I’d suggest not using extract()
. It makes it harder to tell exactly what the available variables are and how they’re set, which is part of the confusion here. Instead, just use $atts
directly. When you do that, any attributes you pass can be accessed on the $atts
array like this:
$id = $atts['id'];
Use shortcode_atts()
to ensure that the accepted attributes have default values so that you don’t get an error if the user doesn’t set the id
on the shortcode.
When you use that approach your shortcode would look like this:
<?php
function post_function( $atts ) {
// Set defaults for attributes.
$atts = shortcode_atts( array(
'id' => 21504,
), $atts );
// Get the ID attribute.
$post_id = $atts['id'];
// Get post by ID.
$post = get_post( $post_id );
// Check there is a post with that ID. If so, return the content, with filters applied.
if ( $post ) {
$content = $post->post_content;
return apply_filters( 'the_content', $content );
}
}
add_shortcode( 'post', 'post_function' );