获取基于Atts的Shortcode的帖子ID

时间:2014-03-31 03:37:14

标签: 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 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是那个自定义帖子类型帖子的slug,我想要抓住ID,我只是不知道怎么比拿那个slug和获取该帖子的ID,以便我可以在$ HeroPostID变量中使用。

2 个答案:

答案 0 :(得分:0)

你试过get_the_ID()吗? 这将给出显示短代码的当前帖子ID

答案 1 :(得分:0)

add_shortcode(' stats',' stats_func'); function stats_func($ atts){

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

//编辑我将如何做到这一点。

相关问题