尝试使用带有短代码和参数的 get_post 来显示 the_content
Trying to display the_content using get_post with a shortcode & parameter
我正在尝试创建一个短代码,它将从特定 post 中提取内容。例如:[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'];
有了 post ID,就可以了
$showcontent = 90;
然而,这是没有意义的,因为我显然希望能够在短代码的参数中输入 ID,而不是直接在我的代码中。
我也尝试删除我的 $showcontent 变量,并改为执行此操作,但这也没有用:
$post = get_post($shortcode_args['show-id']);
$output = apply_filters( 'the_content', $post->post_content );
return $output;
我不明白,为什么要在短代码中应用过滤器?简码函数应该只是 return 值,shortcode-placeholder 将被替换。
以下应该足够了:
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
我正在尝试创建一个短代码,它将从特定 post 中提取内容。例如:[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'];
有了 post ID,就可以了
$showcontent = 90;
然而,这是没有意义的,因为我显然希望能够在短代码的参数中输入 ID,而不是直接在我的代码中。
我也尝试删除我的 $showcontent 变量,并改为执行此操作,但这也没有用:
$post = get_post($shortcode_args['show-id']);
$output = apply_filters( 'the_content', $post->post_content );
return $output;
我不明白,为什么要在短代码中应用过滤器?简码函数应该只是 return 值,shortcode-placeholder 将被替换。
以下应该足够了:
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