I am trying to make a search filter with two post relation ships. i follow this example:
https://toolset.com/forums/topic/display-view-with-filter-on-2-parent-posts/
But the difference is my post relations are many-to-many and not one-to-many as in the example.
I now have this code in functions.php:
add_filter( 'wpv_filter_query', 'filter_by_parent_kommun_func', 999, 3 );
function filter_by_parent_kommun_func( $query_args, $view_settings, $view_id ) {
if ( $view_id == 787 && isset($_GET['wpv-kommun-filter'])) {
$query_args['meta_query'][] = array(
'key' => '_wpcf_belongs_kommun-ramavtal_id',
'value' => $_GET['wpv-kommun-filter'],
);
}
return $query_args;
}
add_filter('wpv_filter_register_url_parameters_for_posts', 'add_extra_url_param_func', 10, 2);
function add_extra_url_param_func($attributes, $view_settings){
if($view_settings['view_id'] == 787){
$attributes[] = array(
'query_type'=> 'posts',
'filter_type'=> 'post_relationship',
'value'=> 'custom_field_value',
'attribute'=> 'wpv-kommun-filter',
'expected'=> 'number',
);
}
return $attributes;
}
And I think the code hangs on " 'key' => '_wpcf_belongs_kommun-ramavtal_id',"
Any suggestions?
Hello,
The thread you mentioned above is using legacy post type relation ship, it won't work in the new post type relationship, and there isn't such a built-in feature to query the posts by multiple post type relationships within UI.
I suggest follow our document to setup the PHP codes
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/how-to-migrate-your-site-to-new-post-relationships/#advanced-example
for example, replace these lines from:
function filter_by_parent_kommun_func( $query_args, $view_settings, $view_id ) {
if ( $view_id == 787 && isset($_GET['wpv-kommun-filter'])) {
$query_args['meta_query'][] = array(
'key' => '_wpcf_belongs_kommun-ramavtal_id',
'value' => $_GET['wpv-kommun-filter'],
);
}
return $query_args;
}
To:
function filter_by_parent_kommun_func( $query_args, $view_settings, $view_id ) {
if ( $view_id == 787 && isset($_GET['wpv-kommun-filter'])) {
if(!isset($query_args['toolset_relationships'])){
$query_args['toolset_relationships'] = array();
}
$query_args['toolset_relationships'][] = array(
'role' => 'child',
'related_to' => $_GET['wpv-kommun-filter'],
'relationship' => 'RELATIONSHIP-SLUG'
);
}
return $query_args;
}
It is only an example for your reference, you will need to replace "RELATIONSHIP-SLUG" with the specific relationship slug.
Hi Luo, You really helped me. But one thing was still off. It did'n work at first because I was working in the archive template. And those listen not to 'wpv_filter_query'. So I changed the hook to 'pre_get_posts', and now it works. Thank you!