• I’m trying to create a link to the current page. I’ve created a shortcode that prints the URL. This works fine. But as soon as I put the shortcode in a link the url is empty and the permalink is displayed as text on the page above where it should be?

    I just want to simply link to the current page permalink. This would be easy but WordPress doesn’t allow PHP in the page/post editor.

    My shortcode function:

    add_shortcode( 'my_permalink', 'my_permalink' );
    // The Permalink Shortcode
    function my_permalink() {
    ob_start();
        the_permalink(2);
    	$permalink = ob_get_clean();
    print(urlencode($permalink));
    }

    [my_permalink]
    Produces the permalink as text but

    <a href="[my_permalink]">link</a>
    creates an empty link and permalink as text.

    • This topic was modified 5 years, 1 month ago by YOELO.
    • This topic was modified 5 years, 1 month ago by YOELO.
    • This topic was modified 5 years, 1 month ago by YOELO.
    • This topic was modified 5 years, 1 month ago by YOELO.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    Why not have your shortcode just return the entire href statement?

    By the way, don’t use ob_* functions in your shortcodes. It can mess with system level caching.

    Thread Starter YOELO

    (@yoebo)

    Thanks, that would be great but I’m not very good with PHP yet does this look OK with the ob_ removed:

    add_shortcode( 'my_permalink', 'my_permalink' );
    // The Permalink Shortcode
    function my_permalink() {
        the_permalink(2);
    print(urlencode($permalink));
    }

    The above code removes the url encoding.
    I will do some further research for including the whole href statement in one shortcode.

    • This reply was modified 5 years, 1 month ago by YOELO.
    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    no, because the_permalink echoes. You cannot “print” directly from a shortcode. Everything must be returned as a string.

    function my_permalink($atts, $content)j {
       return '<a href="'. get_the_permalink() .'">';
    }
    Thread Starter YOELO

    (@yoebo)

    With a bit of tweaking I got it to work. I just need the permalink URL to be encoded as it will be a variable on the end of a Facebook share URL.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Permalink shortcode a href link’ is closed to new replies.