I have a number of views, each of which can apply to many different post types.
I don't want to create a separate view for each of those post types: instead, I want to be able to select which post type to use within the shortcode for that view.
I found some threads explaining how to create a drop-down to select a post type, but I couldn't see how to apply those ideas to my issue.
You could, for example, have the same View which displayed posts according to the post status which was set in an attribute when you insert the View.
But, the post type is not filterable.
When you create a View you specify what kind of content the View will display, and so the post type is effectively hard-wired into the View.
You could create you own solution where you registered a custom shortcode to effectively do the same as the wpv-view shortcode (namely it would receive arguments which you then used to render the View using render_view https://toolset.com/documentation/programmer-reference/views-api/#render_view) and you would also include an attribute for the post type you wanted to query and from within this custom shortcode add a wpv_filter_query filter callback to modify the View arguments and change the post_type).
Nigel will be away for the next few days, so I'll be happy to follow up.
To filter the view's query and make it use a different post type, you don't need a separate shortcode.
You can simply adjust your "wpv_filter_query" function as:
add_filter( 'wpv_filter_query', 'kam_filter_by_post_type', 1000 , 3 );
function kam_filter_by_post_type( $query_args, $view_settings ) {
// check if its the specific view
if ( !is_admin() && ( isset($view_settings['view_id']) && $view_settings['view_id'] == 123) ) {
// get view's shortcode attributes
global $WP_Views;
$attributes = $WP_Views->view_shortcode_attributes;
// if a post type attribute is available
if (!empty($attributes[0]['type'])) {
// set the attribute's value as post type
$query_args['post_type'][0] = $attributes[0]['type'];
}
}
return $query_args;
}
Note: Please replace 123, with your actual view's ID.
After that, you can pass on the slug of your desired post type, using the "type" attribute, in the view's shortcode directly.
Examples:
// make view get post types with slug "books"
[wpv-view name="view-name" type="books"]
// make view get post types with slug "teams"
[wpv-view name="view-name" type="teams"]
// make view get post types with slug "movies"
[wpv-view name="view-name" type="movies"]
I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors: https://toolset.com/contractors/