Snippets: Related Posts by Specific ID’s

This snippet will add a new setting where you can enter the exact ID's for items to display in the related posts section of your blog.

// Add related items setting for standard posts
add_filter( 'wpex_metabox_array', function( $array, $post ) {

	if ( 'post' == $post->post_type ) {

	    $array['main']['settings']['related_post_ids'] = array(
	        'title'         => __( 'Related Posts', 'total' ),
	        'description'   => __( 'Comma seperated ID\'s for related items', 'total' ),
	        'id'            => 'related_post_ids', 
	        'type'          => 'text',
	    );

	}

    // Return fields
    return $array;

}, 40, 2 );

// Alter related items if the related_post_ids meta field is set
add_filter( 'wpex_blog_post_related_query_args', function ( $args ) {
	
	if ( $related = get_post_meta( get_the_ID(), 'related_post_ids', true ) ) {
		$args[ 'category__in' ] = null;
		$args[ 'post__in' ] = explode( ',', $related );
	}

	// Return args
	return $args; 

} );

Result:

Snippet Type: PHP

Posted Under: Blog

All PHP snippets should be added via a child theme's functions.php file.