1

I have many WordPress pages, I am using only one shortcode in those pages, For example the content of page1 is [shortcode name="page1"],

content of page2 is [shortcode name="page2"],

content of page3 is [shortcode name="page3"]

Is it possible that I don't need to specify the name attribute in the shortcode and I can just specify [shortcode] and it takes the title of the page as the name attribute automatically

For example, in plugin, i could write something like this

function shortcode($atts)
 {
 extract(shortcode_atts(array(
'name' => "**title of the page**",
   ) , $atts));

  ......


  }

add_shortcode('short_code', 'short_code');
1

1 Answer 1

1

You can simply use the get_the_title() function to get the current post's title in your shortcode. If you want it to work only on pages, you can combine it with is_page():

function shortcode($atts) {

    extract( 
        shortcode_atts(
            array(
                'name' => get_the_title(),
            ) , 
        $atts) 
    );

    // Rest of your code

}

add_shortcode('short_code', 'short_code');

You can use a PHP shorthand conditional as follows:

'name' => ( is_page() ) ? get_the_title() : 'Your else goes here' ;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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