Since you cannot make a relationship between two posts of the same post type, I've setup a numerical field called 'post-prerequisite' that allows multiple entries and will store the ID of the related post. In my Content Template, I'd like it to load a view for each instance of the prerequisite post ID. Can you suggest a method by which you can do this? Thanks.
- Aaron
Hi Aaron,
Thank you for contacting us and I'd be happy to assist.
To limit the view's results to only include the posts whose ID is saved in the repeating custom field, you can use the filter "wpv_filter_query":
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
For example, suppose you have a "book" post type, in which you have added a numeric repeating custom field "book-related", to store the IDs of the related book posts.
You'll create a new view (suppose the view ID is '12345') in the book post's template, that will be set to show the "Book" posts. The custom filtering function, in this case, would look like this:
add_filter( 'wpv_filter_query', 'wpv_filter_query_func', 1000 , 3 );
function wpv_filter_query_func( $query_args, $view_settings ) {
// process if specific view
if ( ( isset($view_settings['view_id']) && $view_settings['view_id'] == 12345) ) {
// get the IDs of the related posts from field "book-related"
$related_post_id = types_render_field("book-related", array("output" => "raw", "separator" => ","));
// if some related posts are found, set the query to include only those
if(!empty($related_post_id)) {
$related_post_id_arr = explode(',', $related_post_id);
$query_args['post__in'] = $related_post_id_arr;
}
}
return $query_args;
}
You can update this code snippet to use the field slug and the view ID from your website.
The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.
I hope this helps and please let me know if you need any further assistance around this.
regards,
Waqar
My issue is resolved now. Thank you!