post_type_link

Home » Hooks » post_type_link

The post_type_link hook is a powerful WordPress filter that allows developers to modify the permalink structure of custom post types. It provides a way to customize the URL format of individual posts within a specific custom post type.

By using the post_type_link hook, developers can change the structure and elements of the permalink for a custom post type. This hook is particularly useful when you want to create more user-friendly or SEO-friendly URLs for your custom post types.

When WordPress generates the permalink for a specific post within a custom post type, it triggers the post_type_link hook. Developers can then use this hook to modify the generated permalink according to their specific requirements. This can be achieved by appending additional parameters or changing the order of the existing ones.

Example Usage Code:

function custom_post_type_permalink($permalink, $post, $leavename, $sample)
{
    // Check if the post type is "books"
    if ($post->post_type === 'books') {
        // Retrieve the book title
        $book_title = get_post_meta($post->ID, 'book_title', true);

        // Append the book title to the permalink
        $permalink .= '/' . sanitize_title($book_title);
    }

    return $permalink;
}
add_filter('post_type_link', 'custom_post_type_permalink', 10, 4);

In this example, we have a custom post type called "books". The post_type_link hook is used to modify the permalink structure for individual books. The function custom_post_type_permalink takes the current permalink as a parameter, along with the post object, the $leavename flag, and a sample post to determine the structure.

Within the function, we check if the post belongs to the "books" post type. If it does, we retrieve the book title using the get_post_meta function. Then, we append the sanitized book title to the end of the permalink using the sanitize_title function. Finally, we return the modified permalink.

By using the post_type_link hook in this way, we can create custom permalinks for specific posts within our custom post type. This allows us to have more descriptive and SEO-friendly URLs for our books, such as example.com/books/book-title.

Learn More on WordPress.org

WordPress snippets using the post_type_link hook

Register an account to save your snippets or go Pro to get more features.