Php 根据ATT获取短代码的post ID
我想为我的帖子创建一个短码,我可以输入$atts,这将是我自定义帖子类型中的一个slug,我可以使用这个slug来获取帖子的ID,这样我就可以在短码中引入元数据Php 根据ATT获取短代码的post ID,php,wordpress,shortcode,Php,Wordpress,Shortcode,我想为我的帖子创建一个短码,我可以输入$atts,这将是我自定义帖子类型中的一个slug,我可以使用这个slug来获取帖子的ID,这样我就可以在短码中引入元数据 add_shortcode('stats', 'stats'); function stats($atts) { array( 'hero' =>'', ); $HeroSlug = $atts['hero']; $HeroPostID = I need this to grab the post ID based
add_shortcode('stats', 'stats');
function stats($atts) {
array(
'hero' =>'',
);
$HeroSlug = $atts['hero'];
$HeroPostID = I need this to grab the post ID based off the the $atts 'hero' which is the post's slug
$output = echo get_post_meta($HeroPostID 'hero-sub-name', true);
return $output;
}
因此,在短代码中,我会输入[stats hero=“illidan”]illidan是我想要从中获取ID的自定义帖子类型的slug,我只是不知道如何获取slug并获取该帖子的ID,以便我可以在$HeroPostID变量中使用。您尝试过
获取ID()
?
这将给出显示短代码的当前帖子IDadd_shortcode('stats','stats_func');
函数stats_func($atts){
extract(短码)\u atts(数组(
“英雄”=>“
)美元(附件);;
if(strlen($hero)<1){return;}
$theu slug=$hero;
$args=数组(
“name”=>$the_slug,
“post_type”=>“post”,
“发布状态”=>“发布”,
“numberposts”=>1
);
$my_posts=获取_posts($args);
如果($my_posts){
$HeroPostID=$my_posts[0]->ID;
}
}
//编辑我会这样做。我不是在寻找显示短代码的帖子ID,而是它作为英雄放入的slug的帖子ID=“”,所以如果我放入[stats hero=“illidan”我需要slug illidan的帖子ID。在这种情况下,请访问此链接谢谢,这似乎很有效,但我如何才能将输入的内容作为短代码的英雄属性=$the_slug,因为短代码将是[stats hero=“illidan”]或[stats hero=“nova”]我需要把我作为英雄属性的任何东西都放在数组的名称下。啊,是的,我不需要$the_slug,只是在名称下用$HeroSlug替换它,因为它已经被定义并且可以工作。非常感谢。Mark回答:)祝你愉快!你能为我解释这句话“如果(strlen($hero)<1){return;}”它的目的是什么?我还在学习PHP,所以我知道了所有的内容,只是不确定if语句的目的。如果hero的字符串长度(strlen($hero))小于1(即他们没有提供参数),则返回(结束函数),不返回任何内容。
extract( shortcode_atts( array(
'hero' => ''
), $atts ) );
if(strlen($hero) < 1){ return; }
$the_slug = $hero;
$args=array(
'name' => $the_slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if( $my_posts ) {
$HeroPostID = $my_posts[0]->ID;
}
}