Skip Navigation

[Résolu] Filtering View by Post Reference Field Not Working

This support ticket is created Il y a 4 mois et 2 semaines. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

Auteur
Publications
#2459133
Screenshot (58).png

Tell us what you are trying to do?
Filter a View to show posts that are related to a post via a Post Reference field.

Is there any documentation that you are following?
https://toolset.com/documentation/post-relationships/how-to-display-related-posts-with-toolset/#displaying-many-related-items

I have a View that is displaying all Woocommerce Orders and I'm trying to put in a filter to show only the orders that are related to a specific Term post from that CPT. I've added a Post Reference field to the Order type and then added some data to a few of them, then set up a Filter by Post Relationship on the View, but whenever I use it, it shows the list of available Terms, but never returns any results. The filter is working as it filters by the Term ID in the query, so I don't understand why it's not showing me the Orders that have that term in their Post Reference field.

For reference, the Post Reference field is not shown on the View anywhere, but I can't see how this would make a difference. And I haven't used the Post Reference field itself as a filter as it just generates an empty select box.

Here is the filter code:

[wpv-control-post-relationship ancestors="academic-term@order-term.parent" url_param="wpv-relationship-filter"]
<div class="form-group">
	<label for="wpv-relationship-filter">[wpml-string context="wpv-views"]Terms[/wpml-string]</label>
	[wpv-control-post-ancestor type="select" default_label="Select Term" ancestor_type="academic-term@order-term.parent"]
</div>
[/wpv-control-post-relationship]

Everything here is correct, academic-term is the slug of the Term CPT, so I'm assuming order-term would be the generated relationship for this Post Reference field created relationship, and the parent would be the Term, so the one side of the one-to-many.

The URL query looks like this:

?wpv_view_count=3112&wpv-wpcf-order-date_min=&wpv-wpcf-order-date_min-format=d%2Fm%2FY&wpv-wpcf-order-date_max=&wpv-wpcf-order-date_max-format=d%2Fm%2FY&wpv-relationship-filter=427&wpv_filter_submit=Submit

There are also date filters here, but they aren't being set when testing this. You can see the wpv-relationship-filter=427, that's the correct Term post ID for the one being searched for, the Autumn 2022 term, and you can see in the screenshot that at least one Order is set to use this.

I'm really confused why this isn't working as everything seems right, but the response is always zero. Can someone advise where I'm going wrong please?

#2460449

Waqar
Supporter

Languages: Anglais (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi,

Thank you for contacting us and I'd be happy to assist.

To troubleshoot this, I'll need to see how this view and the post reference field are set up in the admin area.

Can you please share temporary admin login details and the link to the page with this view?

Note: Your next reply will be private and making a complete backup copy is recommended before sharing the access details.

regards,
Waqar

#2461531

Minesh
Supporter

Languages: Anglais (English )

Timezone: Asia/Kolkata (GMT+05:30)

As I checked the post reference field setup, You can not filter WooCommerce orders directly.

I've added the following code to "Custom Code" section offered by Toolset with the code snippet namely "search-orders-based-on-term":

function func_filter_orders_by_post_reference_field( $view_args, $view_settings, $view_id )  {
   
  if ( in_array( $view_id, array( 3112 ) ) ) {
    
    $children = toolset_get_related_posts(
        $_GET['wpv-relationship-filter'],
        'order-term',
        array(
            'query_by_role' => 'parent',
            'limit'         => 999,
            'return'        => 'post_id',
            'role_to_return'    => 'child'
        )
    );
    
 
    $view_args['post__in'] = $children;
   // $view_args['post__not_in'] = null;
 
  }
   
  return $view_args;
}
add_filter( 'wpv_filter_query', 'func_filter_orders_by_post_reference_field', 101, 3 );

Can you please check if it works as expected: hidden link

#2462063
Screenshot (59).png

Thank you for the suggestion, it sort of works, but only if you have a search criteria in the Term field. If you use the reset button or load the page without any filter parameters in place it won't load and throws an error:

 E_NOTICE  Undefined index: wpv-relationship-filter

Which relates to the line:

$_GET['wpv-relationship-filter'],

Now I'm sure this could be fixed with a check to see if this is set or not, but I don't understand why this is necessary at all. Help me understand this if you could please.

I completely understand that we cannot query Woocommerce Orders directly, that's the way Toolset functions and this is well documented. This is why I have been adding custom fields to the Order post type to use for this purpose. For example, I wanted to filter the Orders by date, so I have added the Order Date field via Types, as seen in the attached screenshot. This does not query the order directly, instead the linked custom field and allows for the order filtering to work perfectly as described by yourself here:

https://toolset.com/forums/topic/need-an-exposed-filter-for-a-date-range/#post-2254091

All of this makes sense, so I then tried to replicate this with the Post Reference field as using it bypasses the need for additional code, the logic is the same, using a custom post to filter the View. The relationship, order custom field, term custom post type and its fields are all created via Toolset, the actual Woocommerce Order is almost irrelevant to the situation, all it does is have data related to the post ID filtered populate the View via unrelated shortcodes.

So why does this not work? As you have said, I'm not querying or filtering the Order directly, simply Toolset assets that relate to one, exactly like the dates.

Before I spend the time debugging your code suggestion, I'd very much like to understand why this is a problem please. If there is a direct issue then it's something I need to be aware of to avoid in future, but as it stands I can see no reason why this should be a problem.

#2462089

I've just partially confirmed this by adding another custom field for Term ID to the Orders, then manually setting it to the term's post ID, so 427 in this example. Then going back to View and setting up a filter for that field like so:

<div class="form-group">
	<label for="wpv-wpcf-order-term-id">[wpml-string context="wpv-views"]Term ID[/wpml-string]</label>
	[wpv-control-postmeta type="select" field="wpcf-order-term-id" source="custom" url_param="wpv-wpcf-order-term-id" values="427" display_values="Autumn 2022"]
</div>

The only problem I encountered was the same as my initial tests when I tried using post field filter rather than a relationship filter, it had no options in the select field if I set the control type to "Dropdown" and "Using existing custom field values", which I took to mean it would look for existing values and populate the field with them, but I'm now assuming this is not how it works.

When I manually added the values and display_values parameters, it works perfectly.

So what I need to know is why the post reference field does not work for the relationship filtering as outlined in the previous post, and / or if the values and display_values parameters can be filled via custom shortcodes outputting JSON like generic select fields can. I will continue experimenting, but this is where I am at this point.

#2462119

From what I've tested, the parameters will not accept shortcodes as they always seem to exit at the first ending square bracket. For example:

[wpv-control-postmeta type="select" field="wpcf-order-term-id" source="custom" url_param="wpv-wpcf-order-term-id" values="[term_filter_params parameter='values']" display_values="[term_filter_params parameter='display_values']"]

Results in the field being generated empty an then " display_values="Autumn 2022"] being printed to the screen.

Adding these values manually is not a suitable approach as they will vary and definitely be different at different times etc.
I'll await your response from this point to see which is the most viable option to pursue.

#2462141

Minesh
Supporter

Languages: Anglais (English )

Timezone: Asia/Kolkata (GMT+05:30)

Can you please try to use the following code and it should work for reset button as well:

function func_filter_orders_by_post_reference_field( $view_args, $view_settings, $view_id )  {
    
  if ( in_array( $view_id, array( 3112 ) ) ) {
     
if(isset( $_GET['wpv-relationship-filter']) and  $_GET['wpv-relationship-filter'] != ''){
    $children = toolset_get_related_posts(
        $_GET['wpv-relationship-filter'],
        'order-term',
        array(
            'query_by_role' => 'parent',
            'limit'         => 999,
            'return'        => 'post_id',
            'role_to_return'    => 'child'
        )
    );
     
  $view_args['post__in'] = $children;
   // $view_args['post__not_in'] = null;
  
  } 
}
    
  return $view_args;
}
add_filter( 'wpv_filter_query', 'func_filter_orders_by_post_reference_field', 101, 3 );

Regarding using the custom shortcode with Toolset, you will require to register the custom shortcode at:
=> Toolset => Settings => Frontend-Content => Third-party shortcode arguments

#2462323

I always forget to register the shortcodes! That solved that problem.

Your updated code does indeed work, as expected the empty check solved things. But it doesn't display an empty result if a term is selected with no results, and I would need to custom sort the order of the terms.

The shortcode option does allow better control, so I think I may have to go for this. I'll work on it more tomorrow, but in the mean time can I please repeat my question as to why the post reference field doesn't work with the filtering by default and every other field seems to? I would really like an explaination for this please.

#2462807

Minesh
Supporter

Languages: Anglais (English )

Timezone: Asia/Kolkata (GMT+05:30)

Your updated code does indeed work, as expected the empty check solved things. But it doesn't display an empty result if a term is selected with no results, and I would need to custom sort the order of the terms.
==>
I've addressed that by just adjusting the if condition with the filter code I've added:

 if(isset( $_GET['wpv-relationship-filter']) and  $_GET['wpv-relationship-filter'] != '' and $_GET['wpv-relationship-filter'] != 0){

The shortcode option does allow better control, so I think I may have to go for this. I'll work on it more tomorrow, but in the mean time can I please repeat my question as to why the post reference field doesn't work with the filtering by default and every other field seems to? I would really like an explaination for this please.
==>
We entertain only one question per ticket, as your original question for filtering the view with the post reference field is already addressed, May I kindly ask you to open a new ticket with every new question you may have. This will help other users searching on the forum as well as help us to write correct problem resolution summery.

#2462923

Hi Minesh,

I'm afraid my original question was why doesn't the post reference field work like every other field for filtering. And while I am very grateful for the solution, I never actually asked for a fix, I asked for an explanation and have done three or four times since that original post.

Yes, by working through this I can see that my original option was probably more suitable and I simply forgot to register the shortcode, but understanding why the post reference field doesn't work was the original question as this can and will have a bearing on how I try to use this functionality in the future.

So it is not a second question, I'm afraid it has been misread since the start.

#2463841

Minesh
Supporter

Languages: Anglais (English )

Timezone: Asia/Kolkata (GMT+05:30)

I'm afraid my original question was why doesn't the post reference field work like every other field for filtering. And while I am very grateful for the solution, I never actually asked for a fix, I asked for an explanation and have done three or four times since that original post.

Yes, by working through this I can see that my original option was probably more suitable and I simply forgot to register the shortcode, but understanding why the post reference field doesn't work was the original question as this can and will have a bearing on how I try to use this functionality in the future.
==>
The post reference field is treated as child post type internally so technically it will be one-to-many post relationship.

To get child you must select parent first that is why the code I shared was used to query the order-terms (child posts). It seems you removed the post reference field now.

#2465859

I get that it's treated as a post relationship internally, but surely if Views allows you to filter by it, it should default to the current loop item or provide a parameter to set the parent? Either way, I do understand why your code is necessary from that point, but it does seem like a bit of a weird design choice, and it is also not documented anywhere that I could find.

Regardless, you are right I have removed the post reference field as it has proven far easier and more flexible to use a numerical field that I store the term ID in upon order creation, and then I can filter freely and populate the drop-down with a custom sorted list, which works way better than trying to persuade the post reference field to work that way.

Thanks for trying to explain it, but it just doesn't seem to be a developed enough feature to use for this application. I have it fully working with the other approach.