WordPress: echo current post permalink

I coding social sharing buttons in which I want to link current post in single.php template to social media share links.

The problem when I attach the permalink to share url it don`t give the full url of the post:

Read More

I tried http://twitter.com/share?url=<?php the_permalink() ?> but only gave output of /post/69 not http://example.com/post/69.

Any suggetions?

Related posts

4 comments

  1. In WP, you can get permalink of the post with get_permalink() function

    Codex – get_permalink()

    You can use it like that:

    global $post;
    <?php echo get_permalink($post->ID);?>
    

    If you are in TheLoop, which probably is the case, if you are in single.php, then you can use the_permalink() – it will echo the link directly.

    Codex – the_permalink()

  2. Sorry for confusion.

    Everything is working fine except for I am using Prepros live SASS compiler using custom port for preview example.com:4000 which was causing the problem. As long as I switched to standard url example.com, everything is working fine.

    Thanks for all on their precious contributions.

  3. In your WordPress any template, page.php, single.php, serach.php or others page below code will working. get_permalink is WP function and get_the_ID() is also a WP function that will get post id, page id. Try this code.

    try this function into functions.php relative permalink

    function get_relative_permalink( $url ) {
        return str_replace( home_url(), "", $url );
    }
    echo get_relative_permalink(get_permalink(get_the_ID()));
    

    output /post/50/

    or

    function get_relative_permalink( $url ) {
        $url = home_url($url);
        return esc_url($url);
    }
    echo get_relative_permalink($_SERVER['REQUEST_URI']);
    
    http://twitter.com/share?url=<?php echo get_relative_permalink($_SERVER['REQUEST_URI']); ?>
    

    or

    global $post;
    echo get_permalink($post->ID);
    

    or

    the_permalink();
    

    See this link

    See also

Comments are closed.