Get permalink wordpress


Get Permalink By Slug

If you’re looking to get the permalink by the slug, then you need to know two things:

  • A page’s slug is usually the post name unless you’ve done something else programmatically. Review this Codex article for more information.
  • The get_permalink function can accept an ID or an actual object. I’m a fan of passing the ID. I think it makes for cleaner code when comparing it to the Codex documentation.

So with that said, let’s assume that there’s a page that has the slug: “Register For This Site.” Since the slug is often the page’s title, we can write the following function:

 function theme_get_permalink_by_title( $title ) {   // Initialize the permalink value  $permalink = null;   // Try to get the page by the incoming title  $page = get_page_by_title( strtolower( $title ) );   // If the page exists, then let's get its permalink  if( null != $page ) {  $permalink = get_permalink( $page->ID );  } // end if   return $permalink;  } // end theme_get_permalink_by_title 
 if( null == theme_get_permalink_by_title( 'Register For This Site' ) ) {  // The permalink doesn't exist, so handle this however you best see fit. } else {  // The page exists, so do what you need to do. } // end if/else 

Although we’re technically getting the page’s permalink by its slug, the slug is often synoymous with the page’s title so I tend to prefer to write my functions so they are a bit more readable – title seems to be a bit clearer than slug.

Notice also that I’m performing a strtolower within the theme_get_permalink_by_title function. WordPress will handle the case when it’s lowercase and I always find it a best practice to normalize whatever input the user has provided given the function.

I was surfing the WordPress Ideas forum as I usually do every other day or so when I came across an interesting idea for a plugin.

The idea was for an easy way to link to other posts within the same blog without those links ever being broken (even if you change the page/post slug in the future).

This is easy if you have a PHP plugin installed. You just use the get_permalink() function. I suppose not all folks want to mess around with PHP though.

Anyway, 15 minutes later, I had the plugin running and a few tests done.


  • Download

As usual, unzip the get-permalink file. Then, upload it to your /wp-content/plugins directory. Activate it from your WordPress dashboard.

How to use this plugin

The basic syntax is the same as normal hyperlinks, so there shouldn’t be any confusion about how it works.

If you’re just looking for a simple link to a post or page, just add this when writing a post (the 100 is the ID of the post or page):

[permalink href="100"]Hello world![/permalink]

The resulting output would be this:

<a href="" title="Title of your post" rel="bookmark">Hello World!</a>

Well, there’s more you can do, such as define the title, rel, and class of the link. Something like this might suit your fancy:

[permalink href="100" title="Super cool post title" rel="nofollow" class="red-class"]Cool post[/permalink]

How about an image?

[permalink href="100" class="alignleft"]<img src="image.jpg" alt="Example image" />[/permalink]

Why would you need such a plugin?

Well, it’s pretty useless to me since I always keep a PHP plugin installed and can easily use a WP function for this. Plus, I don’t plan on changing too many permalinks anyway.

You might say, “Why not just link directly to the post’s URL?” That’s fine, but if you ever change your permalink structure or change a page/post slug, then you’re in for some trouble. You’ll have broken links.

What happens if you ever decide to change your domain name but want to keep the same posts? Well, your links are protected with this method.

The post/page ID never changes though. So, if you’re linking directly to the ID, your links will always be safe.

It’s not a plugin for everybody, but some might find it useful.

I don’t think there should be any major problems, but I did write this pretty quickly. So, let me know if you run into any trouble, and I’ll fix any issues.

Definition and Syntax

The get_permalink() function makes it possible for you to retrieve the current post’s permalink. It’s syntax goes like below:

 <?php $permalink = get_permalink( $id, $leavename ); ?> 

You see that this function takes two parameters, both optional. The first one, $id, is the one which allows you to manually modify the ID of the post, therefore making you able to choose the post whose permalink you want by it. Obviously, the default value of this parameter is the current post’s ID.

The second one, $leavename, is a boolean operator (that takes either TRUE or FALSE values) that defines the structure of the permalink you will get, or specifically, whether to include the post’s name or just keep the page’s name. To make it more clear, let’s suppose we have set this parameter to FALSE. Instead of getting a result similar to, we will get this one: The default value for this parameter is FALSE.


We mentioned before that we can use the get_permalink() function to get the permalink of both the current post and also others’. Let’s see how we can do these in real life!

Showing current post’s permalink

The easiest and most straightforward way to use the function is to find out the current post’s permalink. See the code snippet below:

 <?php $permalink = get_permalink(); echo $permalink; ?> 

As you might notice, it’s just the syntax, we haven’t defined either parameter.

Showing a certain post’s permalink

We can choose the post whose permalink we want by specifying the $id parameter as seen in the code below:

 <?php $permalink = get_permalink(16); echo $permalink; ?> 

This way, we have required the information regarding the post with the ID 16.

Showing a certain post’s permalink structure

We can find out a specific post’s permalink structure by displaying the post’s permalink with it’s name. Take a look at the code snippet below:

 <?php $permalink = get_permalink(16, true); echo $permalink; ?> 

If the permalink of the post whose ID is 16 is something like when we use the code snippet above, then when we use this line of code it’ll be similar to, or whatever permalink structure you already have set.

Download the source code

This was an example of get_permalink in WordPress.

Download the source code for this tutorial:

get_permalink Function:

get_permalink retrieves the permalink of current post to the frontend as a variable but does not echo it out like the_permalink function. If a permalink of another post is required then post ID can be passed to the function.

<? PHP

$permalink = get_permalink( $id, $leavename );



There are two optional parameters for this function:

  • $id: This parameter gives the developer the freedom of assigning the ID of the desired post, whose permalink is required, manually in integer form. The default is the global $post.
  • $leavename: This parameter provides permalink structure instead of displaying the full permalink and take Boolean operators as inputs (i.e. bool $leavename = false ). The default value is false.


  1. Permalink of a post: In this example, the permalink of the post with id 7 is being retrieved and assigned to variable permalink. Afterwards, the variable’s value is being displayed via echo function.

<? php

$permalink = get_permalink(7);

echo $permalink;


  1. Permalink structure of a post: In this example, the permalink structure of a post is being displayed by assigning $leavename the value TRUE:

<? php

$permalink = get_permalink(5, true);

echo $permalink;


In WordPress, you can easily change the structure of permalinks in the settings sections as shown in the figure below:


The function is used in wp-include/link-template.php, wp-include/embed.php, wp-includes/comment.php, wp-admin/includes/dashboard.php and other files.

The business purpose of using permalinks are to facilitate the search engines and make efficient SEO. The custom structure or post name is the most suitable if you want the site to be SEO efficient.

Tips to use Permalinks:

Prefer underscores (_) to name the posts instead of dashes (-). It will help in SEO. Also use of keywords could help the post in search engine optimization. The most important tip when using permalink is never change them after publishing the post or page. It will affect the traffic at yur website. If it is necessary, then set up a 301 redirection from old URL to new URL via .htaccess. This could also be done via updating the permalinks and saving the file. It will automatically update the .htaccess file.

function get_permalink( $post = 0, $leavename = false ) { 	$rewritecode = array( 		'%year%', 		'%monthnum%', 		'%day%', 		'%hour%', 		'%minute%', 		'%second%', 		$leavename ? '' : '%postname%', 		'%post_id%', 		'%category%', 		'%author%', 		$leavename ? '' : '%pagename%', 	);  	if ( is_object( $post ) && isset( $post->filter ) && 'sample' == $post->filter ) { 		$sample = true; 	} else { 		$post = get_post( $post ); 		$sample = false; 	}  	if ( empty( $post->ID ) ) { 		return false; 	}  	if ( $post->post_type == 'page' ) { 		return get_page_link( $post, $leavename, $sample ); 	} elseif ( $post->post_type == 'attachment' ) { 		return get_attachment_link( $post, $leavename ); 	} elseif ( in_array( $post->post_type, get_post_types( array( '_builtin' => false ) ) ) ) { 		return get_post_permalink( $post, $leavename, $sample ); 	}  	$permalink = get_option( 'permalink_structure' );  	/** 	 * Filters the permalink structure for a post before token replacement occurs. 	 * 	 * Only applies to posts with post_type of 'post'. 	 * 	 * @since 3.0.0 	 * 	 * @param string $permalink The site's permalink structure. 	 * @param WP_Post $post The post in question. 	 * @param bool $leavename Whether to keep the post name. 	 */ 	$permalink = apply_filters( 'pre_post_link', $permalink, $post, $leavename );  	if ( '' != $permalink && ! in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft', 'future' ) ) ) { 		$unixtime = strtotime( $post->post_date );  		$category = ''; 		if ( strpos( $permalink, '%category%' ) !== false ) { 			$cats = get_the_category( $post->ID ); 			if ( $cats ) { 				$cats = wp_list_sort( 					$cats, 					array( 						'term_id' => 'ASC', 					) 				);  				/** 				 * Filters the category that gets used in the %category% permalink token. 				 * 				 * @since 3.5.0 				 * 				 * @param WP_Term $cat The category to use in the permalink. 				 * @param array $cats Array of all categories (WP_Term objects) associated with the post. 				 * @param WP_Post $post The post in question. 				 */ 				$category_object = apply_filters( 'post_link_category', $cats[0], $cats, $post );  				$category_object = get_term( $category_object, 'category' ); 				$category = $category_object->slug; 				if ( $category_object->parent ) { 					$category = get_category_parents( $category_object->parent, false, '/', true ) . $category; 				} 			} 			// show default category in permalinks, without 			// having to assign it explicitly 			if ( empty( $category ) ) { 				$default_category = get_term( get_option( 'default_category' ), 'category' ); 				if ( $default_category && ! is_wp_error( $default_category ) ) { 					$category = $default_category->slug; 				} 			} 		}  		$author = ''; 		if ( strpos( $permalink, '%author%' ) !== false ) { 			$authordata = get_userdata( $post->post_author ); 			$author = $authordata->user_nicename; 		}  		$date = explode( ' ', date( 'Y m d H i s', $unixtime ) ); 		$rewritereplace = 		array( 			$date[0], 			$date[1], 			$date[2], 			$date[3], 			$date[4], 			$date[5], 			$post->post_name, 			$post->ID, 			$category, 			$author, 			$post->post_name, 		); 		$permalink = home_url( str_replace( $rewritecode, $rewritereplace, $permalink ) ); 		$permalink = user_trailingslashit( $permalink, 'single' ); 	} else { // if they're not using the fancy permalink option 		$permalink = home_url( '?p=' . $post->ID ); 	}  	/** 	 * Filters the permalink for a post. 	 * 	 * Only applies to posts with post_type of 'post'. 	 * 	 * @since 1.5.0 	 * 	 * @param string $permalink The post's permalink. 	 * @param WP_Post $post The post in question. 	 * @param bool $leavename Whether to keep the post name. 	 */ 	return apply_filters( 'post_link', $permalink, $post, $leavename ); }

You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.