Related Posts for Custom Post Type Imported from 2nd Site (Harvard Primary Care, Rospods)

Related Posts for Custom Post Type Imported from 2nd Site (Harvard Primary Care, Rospods)

I recently updated a medical school primary care website to a new theme and merged the schools podcast stie into the new site. The old podcast site had a related post feature and I needed Related Posts for Custom Post Type for the new site. I found a nice writeup on “how to” add them at How to display related posts without a plugin but after I implemented it, it didn’t work properly because I had created the Custom Post Type and then imported the Rospod posts as a regular post type before converting them to the custom post type with a plugin. That resulted in both category and tag overlap between the regular post type and the rospod post type.

The two main changes were explictly calling the post type:
[php]
‘post_type’ => ‘rospod’,
[/php]

and then exiting the function if the current post type in the query was not rospod:
[php]
if ( ‘rospod’ != get_post_type() ) {
return;
}
[/php]

The resulting code for the functions.php file looked like this:

[php]
/**
* Related posts
*
* @global object $post
* @param array $args
* @return
*/
function wcr_related_posts($args = array()) {
global $post;

// default args
$args = wp_parse_args($args, array(
‘post_id’ => !empty($post) ? $post->ID : ”,
‘taxonomy’ => ‘post_tag’,
‘limit’ => 3,
‘post_type’ => ‘rospod’,
‘orderby’ => ‘date’,
‘order’ => ‘DESC’
));

// check taxonomy
if (!taxonomy_exists($args[‘taxonomy’])) {
return;
}

// post taxonomies and post types
$taxonomies = wp_get_post_terms($args[‘post_id’], $args[‘taxonomy’], array(‘fields’ => ‘ids’));

if (empty($taxonomies)) {
return;
}
if ( ‘rospod’ != get_post_type() ) {
return;
}

// query
$related_posts = get_posts(array(
‘post__not_in’ => (array) $args[‘post_id’],
//’post_type’ => $args[‘post_type’],
‘post_type’ => ‘rospod’,
‘tax_query’ => array(
array(
‘taxonomy’ => $args[‘taxonomy’],
‘field’ => ‘term_id’,
‘terms’ => $taxonomies
),
),
‘posts_per_page’ => $args[‘limit’],
‘orderby’ => $args[‘orderby’],
‘order’ => $args[‘order’]
));

include( locate_template(‘related-posts-template.php’, false, false) );

wp_reset_postdata();
}
add_action( ‘astra_entry_content_after’,’wcr_related_posts’ );
[/php]

One of the reasons this worked so well is that I had converted the site to the Astra theme. See my post Medical School – Primary Care Elementor & Astra Site Rewrite. The Astra theme has a lot of hooks that allow us to add content programmatically so I was able to use the “astra_entry_content_after” hook to add the content of the related-posts-template.php file to the posts page.