Create Shortcode for the Permalink in WordPress

You can create a shortcode for the permalink in WordPress to use in a string output or more likely as a value for a link attribute, this can be handy if you can’t use PHP in a certain interface.

add_shortcode( 'my_permalink', 'my_permalink' );
// The Permalink Shortcode
function my_permalink() {
ob_start();
    the_permalink();
return ob_get_clean();
}

So you would add this snippet in your themes function.php file and to you the shortcode you would use

[my_permalink]

Or as a link attribute…

<a href=”[my_permalink]” >CLICK ME</a>

2 Comments

  1. Damien Carbery on April 26, 2018 at 8:27 am

    Could you use get_permalink() and remove the ob_start/ob_get_clean calls?
    https://developer.wordpress.org/reference/functions/get_permalink/

    As this will return a link to the current post, what use cases do you see with this shortcode?

    • Neil Gowran on April 26, 2018 at 8:45 am

      Hi Damien – one use case for me was for using the shortcode in a loop with conditional code in Beaver Themer loops in the Posts Module, custom layout – so I could manipulate the permalink used in a read more link. Regards the use of object buffering, dependent on your output you can use or not use.

Leave a Comment