April 17, 2015 in Snippets, Wordpress

Shortcode to get page URLs

We usually need to add interlinking between different pages of a website. WordPress provides a wonderful mechanism to add links between pages. But sometimes we need more control over the links.

This shortcode makes it easy to find URL of a page, by it’s ID, Slug, or Title.

<?php
function easy_permalink($atts) {
    extract(shortcode_atts(array(
        'id' => -1,
        'slug' => "",
        'title' => ""
    ), $atts));
 
    if ($id && $id != -1) {
        return get_permalink($id);
    } elseif($slug) {
        return get_permalink( get_page_by_path( $slug ) );
    } elseif($title) {
        return get_permalink( get_page_by_title( $title ) );
    } else {
        return "#";
    }
}
add_shortcode('permalink', 'easy_permalink');
?>

How to use:

<a href="[permalink id="9"]">Link Here</a>
 <a href="[permalink slug="/about-us/careers/"]">Link Here</a>
 <a href="[permalink title="Careers"]">Link Here</a>

Note: If you are not familiar with wordpress themes, you need to add this code in functions.php in your theme’s folder.

About the author

Alok Jain

Alok designs digital experiences to help businesses achieve their goals. He is passionate about designing the right User Experience for their customers. For over 15 years, he has worked with small startups to mature product teams. Whether it is designing a WordPress product, a frontend experience, WooCommerce, or React.js, he follows the best product development practices for design and code, for desktop or mobile.

One thought on “Shortcode to get page URLs

  1. It’s very easy to find out any topic on net as compared to books, as
    I found this article at this site.

Leave a Reply

Your email address will not be published. Required fields are marked *