Wordpress短代码功能仅返回标题

问题描述 投票:0回答:2

我的问题是:尝试使用简单的shortcode函数检索the_content,它仅检索标题。即使应用其他过滤器,结果也始终相同。

  • 内容来自页面。
  • 该函数在functions.php主题文件中声明。
  • 使用帖子(页面)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');
    

使用[shortcodePage id=POST_ID] (int)从小部件中调用

结果:仅打印标题。我尝试使用“ the_post_thumbnail”更改过滤器,然后再次检索了标题。

我很绝望:(

谢谢!

php wordpress shortcode
2个回答
1
投票

您的简码功能有些错误,但主要是:

  1. 您正在使用extract,但未使用extract中的任何内容>
  2. [$atts是一个数组,而不仅仅是id
  3. 您正在使用apply_filters('the_content')。这实质上将覆盖apply_filter中内置的WP。您想使用add_filter,但是您将看到不需要。
  4. 这里是根据您要执行的操作精简的简码:

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');

0
投票
Try to use like this: 
function shtcode_Func( $atts = array() ) {

    // set up default parameters
    extract(shortcode_atts(array(
        'id' => '5'
    ), $atts));

    ob_start();
    $content_post = get_post( $atts['id'] );
    $content = $content_post->post_content;
    $content = apply_filters( 'the_content', $content );
    $content = str_replace( ']]>', ']]>', $content );
    echo $content;
    $str = ob_get_contents();

    ob_end_clean();

    return $str;
}

add_shortcode('shortcodePage', 'shtcode_Func');
© www.soinside.com 2019 - 2024. All rights reserved.