0

I want to be able to create a shortcode that will return the post title when I pass in the ID of the post. I.E. [myshortcode_title ID=1234]

I have a shortcode that pulls the post title from the current post:

function myshortcode_title( ){
   return get_the_title();
}
add_shortcode( 'page_title', 'myshortcode_title' );

I've seen shortcodes that can pass in attributes and return a result outside the loop, but I'm still new at WP shortcodes.

0

Codex documentation for shortcodes has a section on Handling Attributes.

In a nutshell attributes will get passed on to your callback and you need to implement handling them with your code within it:

function my_shortcode_handler( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'attr_1' => 'attribute 1 default',
        'attr_2' => 'attribute 2 default',
        // ...etc
    ), $atts );
}
  • I didn't know I'd have to extract and store the ID into an array to do this. I was hoping it was a simple lookup I could use. – Adam Costanza Jul 24 '17 at 16:30
  • The extraction will be performed by WP for you. This is relatively easy in practice once you figure basics of it. :) – Rarst Jul 24 '17 at 16:33
0

This is what I used to get the result I want which is post title by passing in post ID:

// Get Post Title outside of loop
// USE: [get-post-details post="123"]

function title_by_id($atts) {
    $atts = shortcode_atts( array(
        'post' => 0,
    ), $atts, 'title-from-id' );   
    $id = $atts['post'];               
    $data = get_the_title($id);        
    return $data;                      
}
add_shortcode( 'title-from-id', 'title_by_id' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.