【问题标题】:Trying to display the_content using get_post with a shortcode & parameter尝试使用带有简码和参数的 get_post 显示 the_content
【发布时间】:2022-01-28 14:30:07
【问题描述】:

我正在尝试创建一个从特定帖子中提取内容的简码。例如:[show_my_content show-id="90"]

这是我的代码。但有些不对劲:

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

但是,如果我替换以下变量的值:

$showcontent = $shortcode_args['show-id'];

有一个帖子ID,然后就可以了

$showcontent = 90;

但是,这是没有意义的,因为我显然希望能够在短代码的参数中输入 ID,而不是直接在我的代码中。

我也尝试删除我的 $showcontent 变量,并改为这样做,但这也没有用:

$post = get_post($shortcode_args['show-id']);
$output = apply_filters( 'the_content', $post->post_content );
return $output; 

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    我不明白,您为什么要在短代码中应用过滤器?简码函数应该只返回值,简码占位符将被替换。

    以下应该足够了:

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

    如果您愿意,还可以阅读简码文档: https://codex.wordpress.org/Shortcode_API

    【讨论】:

    • 谢谢。我对此非常陌生,所以仍在尝试弄清楚。不幸的是,您的代码不起作用。我收到以下错误:“致命错误:未捕获的错误:函数 shortcode_atts() 的参数太少,通过了 1 个”
    • @Shtarley 抱歉,我犯了一个错误,但我已修复它。你能再试一次吗? :)
    • 成功了,谢谢
    • 酷,如果你能接受这个答案,那该多好 :)
    猜你喜欢
    • 2018-01-30
    • 2016-05-24
    • 2021-12-25
    • 2017-01-15
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多