PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] Trying to display the_content using get_post with a shortcode & parameter

 February 05, 2022     php, wordpress, wordpress-theming     No comments   

Issue

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; 

Solution

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



Answered By - Kevin Glier
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing