I am trying to create a shortcode that will pull the content from a specific post. For example: [show_my_content show-id="90"]
This is my code. But something is wrong:
// Creating Shortcode
function show_my_content_shortcode ($attr, $content = null){
global $post;
// Define Shortcode Attributes
$shortcode_args = shortcode_atts(
array(
'show-id' => '',
), $attr);
$showcontent = $shortcode_args['show-id'];
$post = get_post($showcontent);
$output = apply_filters( 'the_content', $post->post_content );
return $output;
}
add_shortcode( 'show_my_content', 'show_my_content_shortcode' );
?>
However, if I replace the value of the following variable:
$showcontent = $shortcode_args['show-id'];
with a post ID, then it works
$showcontent = 90;
However, this is pointless, because I obviously want to be able to enter the ID in the parameter of the shortcode, and not directly in my code.
I also tried to remove my $showcontent variable, and to do this instead, but this also didn't work:
$post = get_post($shortcode_args['show-id']);
$output = apply_filters( 'the_content', $post->post_content );
return $output;
I don't understand, why you are applying a filter within the shortcode? The shortcode function should just return the value and the shortcode-placeholder will be replaced.
Following should be enough:
add_shortcode('show_my_content', function ($attr) {
// Define Shortcode Attributes
$shortcode_args = shortcode_atts(['show-id' => ''], $attr);
$content = get_post_field('post_content', $shortcode_args['show-id']);
return $content;
});
Read also the documentation for shortcodes, if you like: https://codex.wordpress.org/Shortcode_API