How to Get the URL of a Post Type Archive in WordPress
The function get_post_type_archive_link
returns the URL of a post type archive in WordPress.
Post type archive
A post type archive includes exclusively the posts that belong to the same post type. If a post type archive is requested, WordPress queries the database and returns the posts that belong to the post type.
Example: On this website I use the post type Tutorial to group tutorials. The archive of this post type is available at rafaelcardero.com/tutorials/.
Syntax
get_post_type_archive_link($post_type)
returns the URL of the archive for the post type $post_type
. If $post_type
is not a registered post type or has no archive, the result is FALSE
.
// Get the URL of the archive for the post type Post
$example1 = get_post_type_archive_link('post');
// Get the URL of the archive for a post type registered as 'ns_book_cpt'
$example2 = get_post_type_archive_link('ns_book_cpt');
Issues
If you get FALSE
, check that $post_type
is the identifier of a registered post type, and that the 'has_archive'
attribute was set to TRUE
when the post type was registered.
By default WordPress uses as slug the identifier of the post type, which sometimes looks ugly. You can change this slug specifying a value for the 'slug'
member of the 'rewrite'
attribute when the post type is registered.
Learn here how to change the slug of a post type in WordPress.
Further reading
I recommend the other tutorials in this series to learn more about post types in WordPress.
- Post Types in WordPress
- How to Register a Custom Post Type in WordPress
- How to Register a Custom Post Type Using a Plugin in WordPress
- How to Unregister a Custom Post Type in WordPress
- How to Modify a Post Type in WordPress
- How to Change the Slug of a Post Type in WordPress
- How to Check if a Post Type Exists in WordPress
- How to Get the Registered Post Types in WordPress
- How to Get the Attributes of a Post Type in WordPress
- How to Get the URL of a Post Type Archive in WordPress
- How to Add Custom Post Types to the Main Query in WordPress
Source code
The source code developed in this tutorial is available here.
Comments