How To Get WordPress Permalinks Using PHP?

There are plenty of information on the internet regarding how to use permalinks for SEO. Unfortunately, I did not come across any that detailed all of the helpful functions accessible in the WordPress API, such as getting the permalink value.

The most popular permalink-related method is, of course, get_permalink() However, there are many additional functions offered in the WordPress API that you may use in your project. Most of these may be found in the WordPress documentation, however it might be pretty difficult to find all of the information you are looking for there.

The following article is a summary of the most significant and often used PHP functions allowing to get permalinks for post, categories, archives, and navigation in general. You will learn how to get an archive link in WordPress, for example, by using the functions described below.

For the sake of completeness, I will say up front that the information in this post is meant for everyone working with WordPress, not just those using the Permalink Manager. Another thing to keep in mind is that the list may not cover all of the WordPress permalink API's available functions. Listed below are the most commonly used and essential functions for custom development.

Post, term and archive permalinks

get_permalink($post, $leavename);
Variable Description
$post Post identifier or object. If empty, the global $post variable will be used. (int|WP_Post)
$leavename If set true, the post/page name tag will be preserved. False by default (bool)

This is the most often used permalink function, which is used in the vast majority of plugins and themes. The function outputs the complete URL of any post, page, or custom post item. More information is available in the WordPress documentation, which you can access by clicking here.

For example, if you want to get the permalink for a post with an ID of 123, you would use the following code. The function returns the permalink as a string, which you can then use to create a link to the post:

$permalink = get_permalink(123);
echo '<a href="' . esc_url( $permalink ) . '">View post</a>';

In addition to the get_permalink(), an alias function called get_the_permalink() is also available. Both functions share the same set of variable inputs.

Alternatively, you may call specific functions such as get_post_permalink() for posts and custom post type items, get_page_link() for pages and get_attachment_link() for attachments.

get permalink function in Rank Math plugin
The get permalink() function in action. A meta tag with a canonical URL is generated using this function by Rank Math plugin in the <head> section of HTML source.

Get shortlink of post/page

wp_get_shortlink($post_id, $context = 'post', $allow_slugs = true);
Variable Description
$post_id Post identifier. If empty, the global $post->ID variable will be used. (int)
$context When this optional argument is set 'query' and function called on a single post page, the current query is used to determine the ID. (string)
$allow_slugs This optional argument is used only if the shortlink URL is modified with 'pre_get_shortlink' or 'get_shortlink' filters (bool)

This function is similar to the get_permalink() function, but it returns a shorter URL that is intended to be more convenient for sharing.

The primary goal of wp_get_shortlink() function is to generate a shortlink URL that is limited by default to providing "?p=123" style links for posts. The pre_get_shortlink and get_shortlink filters in plugins may be used to change the shortlink format.

Get the ID of a post or page from its URL

As a WordPress developer, you may need to extract the ID of a post or page from its URL. For example, you may need to get information on a single post or page, such as its title or content, or you may need to write a custom query that picks posts or pages based on their URLs.

In such circumstances, the url_to_postid() function might be a valuable asset to have on hand.

url_to_postid($post_url)
Variable Description
$post_url The full URL of the post or page (string)

Using WordPress's url_to_postid() function is a fairly straightforward process. The function may be called straight from your WordPress template files or plugin code. In the example below, we use the url_to_postid() function to get the post ID for the sample post URL. The get_the_title() function is then used to access the post title for that ID, which is then shown using the echo statement.

$url = 'https://www.example.com/sample-post/';
$post_id = url_to_postid( $url );
$post_title = get_the_title( $post_id );
echo $post_title;
get_term_link($post, $taxonomy);
Variable Description
$term The term object, ID, or slug for which a link needs to be found. (WP_Term|int|string)
$taxonomy The taxonomy of term provided in the first argument. (string)

A term archive page is a type of archive page that lists all the posts in a particular taxonomy term. For example, if you have a taxonomy called "genre" and a term called "horror", a term archive page for the "horror" term would list all the horror-related posts on your site.

The get_term_link() method is similar to the get_permalink() function, except it returns the complete URL address of a single term.

The following is a list of three fundamental PHP functions that may be used to get the whole URL of the most frequently used archive links in WordPress. You may use them to lead your visitors to pages on your site that show all of the posts or items that belong to a custom post type.

Get post type archive URL

get_post_type_archive_link($post_type);
Variable Description
$post_type The name (slug) of the post type for which a URL to the archive page is to be found. (string)

A WordPress page that lists all the posts of a particular post type is called a post type archive page. The get_post_type_archive_link() function takes a single argument: the name of the post type for which you want to get the archive link.

For example, if you want to get the archive link for the "product" post type, you can use the following code.

The function returns the archive link as a string, which you can then use to create a link to the post type archive page:

$archive_link = get_post_type_archive_link('post');
echo '<a href="' . esc_url( $archive_link ) . '">View all products list</a>';

This information is just a hint. If you want to know more about how to get the archive link for content types, you can find all the details in the WordPress documentation. Go here for further information about get_post_type_archive_link() function.

Archive link sample
Its most visible use is in WooCommerce, where it is used to generate a URL link that allows customers to navigate to the main “store” page. Technically, “store” is a post type archive page for “products”.

Author archive page URL

get_the_author_meta('user_url', $user_id);
Variable Description
$field = 'user_url' To acquire the archive URL, set the first parameter to 'user url'. (string)
$user_id The ID of the user whose archive URL is required. (integer)

In contrast to the previously described functions, generating a URL for an author archive takes a little more finesse. To do this, use the get_the_author_meta() function and pass 'user url' as the first parameter.

Get author archive URL
You can use get_the_author_meta() function to get author archive URL and display it on single post page.

As you can see, each of the above-mentioned content kinds has its own dedicated function that returns the URL address. There are times when you need to provide the URL of the blog page where the posts are displayed.

wordpress get blog page permalink
In order to get a permalink for a blog page in WordPress, you must first choose it in the settings.

If you want that, you will have to merge two separate functions. In more specific terms, you will need to get the ID of the blog page that you chose previously in the "Settings -> Reading" admin section of WordPress. Then, you need to utilize that page ID as an input for the second line.

$blog_page_id = get_option('page_for_posts');
$blog_page_url = get_permalink($blog_page_id);

The first line of code, retrieves the ID of the blog page. The get_option() function is a WordPress function that retrieves an option value from the WordPress database. Then, the second line of code, retrieves the permalink (URL) of the blog page using the get_permalink() function and the post ID of the blog page.

Once the code has been executed, the $blog_page_url variable will contain the permalink for the blog page as a string. You can then use this URL to create a link to the blog page, like this.

echo '<a href="' . esc_url($blog_page_url) . '">View blog</a>';

It is worth to mention that the esc_url() function is used to sanitize a URL before it is output in an HTML page. This is important because a URL that is not properly sanitized can create vulnerabilities in your website that can be exploited by attackers.

Homepage and template URLs

In most circumstances, get_home_url() and get_site_url() will return the same URL and may be used interchangeably. However, if you keep the WordPress source files in a separate folder, pay attention to the function you are using. If you are still confused, check out this StackOverflow discussion for a more in-depth explanation.

Get homepage URL
If you keep your WordPress files in the main directory, you may use both functions in the same manner.

Homepage URL address

get_home_url($blog_id = null, $path = '', $scheme = null);
Variable Description
$blog_id If you are not using network/multisite configuration, leave this field empty. (integer)
$path Path relative to the home URL. (string)
$scheme Accepts 'http,' 'https', 'login', 'login post', 'admin', or 'relative' as parameters. (string)

To get a homepage link please use the get_home_url() function. There is also a "shortcut" function available: home_url() . The function returns the value defined in the "Settings -> General" panel as the "Site Address". This function may come in handy if you want to provide a link to the front page in the navigation elements: breadcrumbs, sidebar or navbar.

WordPress files directory URL

get_site_url($blog_id = null, $path = '', $scheme = null);
Variable Description
$blog_id If you are not using network/multisite configuration, leave this field empty. (integer)
$path Path relative to the home URL. (string)
$scheme Accepts 'http,' 'https', 'login', 'login post', 'admin', or 'relative' as parameters. (string)

This function returns the URL address of the directory where WordPress plugin files are stored. You can also use an alias function: site_url() . The function returns the address specified in the "Settings -> General" field in the "WordPress address (URL)" panel.

WordPress (child/parent) theme directory URL

get_stylesheet_directory_uri(); // Get child theme URL
get_template_directory_uri(); // Get parent theme URL

If you do not use a child theme, get_stylesheet_directory_uri() and get_template_directory_uri() will both return the same URL and may be used alternatively.

To put it another way, if you have a child theme installed, use get_stylesheet_directory_uri() to get the URL containing its directory. The get_template_directory_uri() function may be used to get the parent directory URL.

Both of these functions are useful for including resources (such as CSS or JavaScript files) in your theme. For example, you might use the get_stylesheet_directory_uri() function to link to a CSS file in your theme like this:

wp_enqueue_style( 'my-theme-style', get_stylesheet_directory_uri() . '/style.css' );
Proper way to enqueue scripts and styles.
Both functions may be useful if you need to enqueue certain static files (images, JS, CSS) to the website.

How to sanitize URL addresses?

esc_url($url, $protocols = '');
Variable Description
$url If you are not using network/multisite configuration, leave this field empty. (string)
$protocols Path relative to the home URL. (array of strings)

You should always use esc_url() to sanitize URLs in HTML nodes (eg. <a href="">). The function will also reject URLs that do not use one of the whitelisted protocols: http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet. Invalid and potentially harmful characters will be automatically secured from input. For instance, ampersands (&) and single quotation marks (') will be encoded as numeric entity references (&#038, &#039).

The importance of sanitizing URLs output in HTML?

For example, if you are creating an HTML anchor tag using a URL that has not been sanitized, an attacker could potentially inject malicious code into the URL that would be executed when the link is clicked. This could lead to security issues such as cross-site scripting (XSS) attacks, where an attacker is able to execute malicious code on your website.

By sanitizing the URL before it is output, you can help protect your website and your users from potential security risks. It's a good practice to use this function whenever you are outputting a URL in an HTML page, to ensure that the address is safe and secure.

Summary

WordPress offers a range of functions that enable users to retrieve and display links to particular content within their website. These functions can be utilized to create links to individual posts and pages, as well as to archive pages for terms within taxonomies and post types.

The use of these functions can be beneficial in a number of situations, including linking to specific content within the website, directing users to a list of posts within a specific taxonomy term, and displaying all posts within a particular post type.

by Maciej Bis

Leave a Reply

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