wp-shortcake / shortcake

Shortcake makes using WordPress shortcodes a piece of cake.
GNU General Public License v2.0
665 stars 143 forks source link

Submits all shortcode fields for AJAX searches. #767

Open jaredcobb opened 6 years ago

jaredcobb commented 6 years ago

When creating a custom Post Select field (that extends the existing Shortcode_UI_Field_Post_Select class) it would be very helpful to also send all other shortcode fields in the AJAX request.

A use case would be to allow users to customize the WP_Query args in the UI itself when searching for posts. For example, we can provide dropdowns for date_query options such as "After/Before", "-30 days, -7 days, -24 hours", etc.

It would be the responsibility of the shortcode class to sanitize and perform logic for the extra data. This shouldn't affect any existing shortcodes as the extra data would simply be ignored in the current AJAX callbacks.

goldenapples commented 6 years ago

This is interesting, and I can see the usefulness of it, especially in the example you give of using a field to narrow down the query args for posts being searched.

My only thought is that just serializing the whole form seems a little clumsy. I can't find any security issues with it, since $.serialize handles url-encoding of special characters, but it seems like you'd be getting a lot more data than you're likely to need. I was wondering if a hook where you could filter the ajaxData object before sending it would be more useful.

jaredcobb commented 6 years ago

@goldenapples I like that idea. Do you have a suggestion on the implementation of a hook like that? (I'd be happy to update the PR). Do you mean a WordPress hook? Or something in JavaScript?

I initially felt the same way as you about serialize() but wasn't sure of a better way to capture the fields without hardcoding each value. At least in my scenario the shortcode UI never has more than just a few fields (so the payload in the AJAX call wasn't overwhelming from a network standpoint).

goldenapples commented 6 years ago

I posted an example of the js filter structure we use elsewhere at #768. I'm not sure how helpful it is for the use case you want, or how cumbersome it would be to have to enqueue the extra javascript on the post edit screen for your custom attribute field. Feel free to crib from it if it could be modified to be helpful in the use case you're looking for.

If not, I think something along the lines of what you have here could be fine too. The only thing I see that might be an issue is that some field types don't have a native form element that would be picked up with '.serialize()'. (As an example, I'm noticing the post select field doesn't have a "name" element, so if you were trying to exclude posts that had already been selected for another attribute, you couldn't do that with the form.serialize approach....)