17th April 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 design digital experiences to help businesses achieve their goals. He is passionate about designing right User Experience for their customers. For over 15 years, he have worked with small startups to mature product teams. Whether it is designing a WordPress product, a frontend experience, WooCommerce, Shopify, he follow the best product development practices for design and code, for desktop or mobile.