Shortcode for pulling specific Post Title outside loop when ID is passed in

admin2025-01-07  4

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.

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.

Share Improve this question edited Jul 24, 2017 at 17:14 bravokeyl 3,3776 gold badges27 silver badges33 bronze badges asked Jul 24, 2017 at 15:29 Adam CostanzaAdam Costanza 11 bronze badge 1
  • See related: wordpress.stackexchange.com/questions/58438/… – WebElaine Commented Jul 24, 2017 at 15:38
Add a comment  | 

2 Answers 2

Reset to default 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 );
}

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' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736255712a303.html

最新回复(0)