Question

I'm looking to create a shortcode for my Posts that I can input an $atts which would be a slug for a post in my custom post type which I can than use that slug to get that post's ID so I can pull in meta data in the shortcode.

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

So in the shortcode I would put in [stats hero="illidan"] illidan is the slug for that custom post type post that I want to grab the ID from I'm just not sure how to than take that slug and grab the ID of that post so I can use in the $HeroPostID variable.

Was it helpful?

Solution

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

//edit That's how i would do it.

OTHER TIPS

Have you tried get_the_ID() ? This will give the current post ID on which the shortcode is being displayed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top