Skip to content
Advertisement

WordPress shortcode function returns only the title

my problem is that: Trying to retrieve the_content with a simple shortcode function, it retrieves only the title. Even applying another filters the result is always the same.

  • The content is from a page.
  • The function is declared in the functions.php theme file.
  • Using the post (page) id.

        function shtcode_Func( $atts = array() ) {
    
      // set up default parameters
       extract(shortcode_atts(array(
        'id' => '5'
       ), $atts));
    
       $my_postid = $atts;//This is page id or post id
       $content_post = get_post($my_postid);
       $content = $content_post->post_content;
       $content = apply_filters('the_content', $content);
       $content = str_replace(']]>', ']]>', $content);
    
       return $content;
    }
    
    add_shortcode('shortcodePage', 'shtcode_Func');
    

Calling from widget with [shortcodePage id=POST_ID] (int)

Result: Prints only the title. I tried to change the filter with ‘the_post_thumbnail’ and retrieved the title again.

I’m desperated 🙁

Thanks!!

Advertisement

Answer

There are several things incorrect with your shortcode function, but the main things:

  1. You are using extract but not using anything from extract
  2. $atts is an array, not just the id.
  3. You are using apply_filters('the_content'). This essentially overwrites WPs built in apply_filter. You want to use add_filter, but as you can see that won’t be necessary.

Here is the shortcode trimmed down with what you are trying to do:

function shtcode_Func( $atts ) {

    // set up default parameters. No need to use extract here.
    $a = shortcode_atts(array(
        'id' => ''
    ), $atts);

    // Use get_the_content, and pass the actual ID
    $content = get_the_content('','', $a['id'] );
    // This is the same
    $content = str_replace(']]>', ']]>', $content);
    // Return the content.
    return $content;
}

add_shortcode('shortcodePage', 'shtcode_Func');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement