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

As a Frontend Developer and Founder, I blend technical skills with entrepreneurial drive. Skilled in crafting intuitive user interfaces, I bridge design and development for seamless digital experiences. Beyond work, I'm passionate about Philately, sharing my collection, and connecting with fellow enthusiasts in both tech and stamp collecting communities.

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 *