Views plugin provides an API, making it easy to display Views output using PHP.
When you ask for help or report issues, make sure to tell us all related information about your View and the data that you want to display using the Views API.
Problem: I have custom fields in two different post types that contain similar values. I would like to filter post type A by the custom field value in post type B.
Solution: Use a Query Filter that responds to a shortcode attribute, and set the attribute value using the raw types field data from the current post type.
Problem: I have a View and I want to ensure that 4 results are always displayed. I can set a limit of 4, but I would also like to know how to append random results as needed if the number of results is less than 4.
Solution: Use the Views Filter wpv_filter_query_post_process to manipulate the result set programmatically. Use WP_Query to fetch random results that aren't included in the results already, and then append those to the current results. Example:
add_filter( 'wpv_filter_query_post_process', 'nh_modify_related_gt_query', 10, 3 );
function nh_modify_related_gt_query( $query, $view_settings, $view_id ) {
if( $view_id = '22313' ) { // Applies to "Related Glossary Terms (4)" view
if ( sizeof( $query->posts ) < 4 ) { // if the query has less than 4 related terms
$fillsize = 4 - sizeof( $query->posts );
$post_ids = wp_list_pluck( $query->posts, 'ID' );
$args = array(
'post_type' => 'glossary',
'posts_per_page' => $fillsize,
'post__not_in' => $post_ids,
'orderby' => 'rand',
'no_found_rows' => true
);
$fillquery = new WP_Query( $args );
$initposts = $query->posts;
$randposts = $fillquery->posts;
$filled_terms = array_merge($initposts, $randposts);
$query->posts = $filled_terms; // add the random posts at the end of the posts result array
$query->found_posts = 4; // modify the count of found posts
$query->post_count = 4; // modify the count of displayed posts
}
}
return $query;
}