WordPress uses various functions to facilitate its users in delivering the best. Among various functions get_permalink is the one and holds importance one way or another. In WordPress theme or plugin, if the post permalink is required then get_permalink() function is used.

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 );

?>

Parameters:

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.

Examples:

  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:

get-permalink-1

Uses:

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.