How to use the_permalink() in WordPress

The the_permalink() function is a built-in WordPress function that outputs the URL of the current post or page. It is commonly used in WordPress theme development to generate links to single post or page views.

Here’s how to use the the_permalink() function in WordPress:

  1. Open the template file where you want to display the permalink (for example, single.php or page.php).
  2. Find the location in your code where you want to display the permalink. This could be inside an HTML link, a button, or just as plain text.
  3. Inside that location, use the the_permalink() function to output the URL of the current post or page. Here’s an example:
html
<a href="<?php the_permalink(); ?>">Read More</a>

This code will generate an HTML link that points to the current post or page, using the the_permalink() function to output the URL.

You can also use the get_permalink() function to retrieve the permalink URL as a string, rather than outputting it directly to the page. This can be useful if you need to manipulate the URL before displaying it.

Here’s an example:

php
<?php $permalink = get_permalink(); ?>
<a href="<?php echo $permalink . '#comments'; ?>">Jump to Comments</a>

In this example, we’re retrieving the permalink URL using get_permalink(), storing it in a variable, and then appending #comments to the end of the URL to create a link that jumps directly to the comments section of the post.

Overall, the_permalink() is a simple but powerful function that can help you generate links to your WordPress posts and pages with ease.