Skip to content
Advertisement

How to build a WordPress archive template to show an author’s multiple post_types in single template?

In my WordPress v5.7, currently I have two custom post_type: song, & poem.

I have a custom author.php template with author profile and latest 10 posts from both post_type with no pagination, as required by site design. Here is the author template at pastebin (https://pastebin.com/kCrYebcD).

If the author has more than 10 posts from both post_type, I want to show all posts from both post_type in archive.php template with pagination. Here is the archive template at pastebin (https://pastebin.com/twkWn5Bc).

In author.php I have this URL to redirect to all post archive page:

<?php
$author_page_link = esc_url(get_author_posts_url(false, ID->user_nicename));

echo '<a href="' . $author_page_link . '?post_type[]=song&post_type[]=poem">All</a>';
?>

This is how the URL constructs: http://www.local.site/author/one/?post_type[]=song&post_type[]=poem.

The above URL is redirecting back to author.php page. If I use only any one post type as below, the URL stays in the archive.php.

<a href="' . $author_page_link . '?post_type=poem">All</a>

How can I show a single author’s all posts from selective custom post_type in the archive.php?

Advertisement

Answer

This is how I have solved:

I have created a custom page template author-all-posts.php with page slug all. I have used the custom URL parameters as below:

http://www.local.site/all/?author_id=1

In my custom page template, I have the below code:

// get the author ID
$authorID = $_GET['author_id'];

Below the WP_Query to get all the posts from multiple post_types:

$all_args = array(
    'author' => $authorID,
    'post_type' => array('song', 'poem'),
    'posts_per_page' => -1
);
query_posts($all_args);

I am working on add_rewrite_rule to red rid of the ugly URLs next.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement