Support

Account

Home Forums General Issues JS prepare_for_ajax problem in acf_form

Solved

JS prepare_for_ajax problem in acf_form

  • Hi there, i have custom acf_form field displayed in frontend form. It’s post_object field with select2. I want user to select post, and append it to the page using custom js (already working).
    Problem is, i want select2 to EXCLUDE already appended posts. So i found acf.add_filter(‘prepare_for_ajax’) and wrote something like this:

    acf.add_filter(
    	'prepare_for_ajax',
    	function(args) {
    		//here custom loop is getting IDs of posts already in the page as "exclude" var, it's either empty array, or array with IDs, no problem with this variable
    		args.post__not_in = exclude.join(); //i've tried joining so it will be exploded in php later, no use...
    		return args;
    	}
    );

    This is triggered each time i’m clicking on select2 field, so everything is ok, args.post__not_in is set like i want it to.

    And because i saw in console log it’s calling acf/fields/post_object/query i hooked into there in functions.php:

    function relationship_options_filter($args, $field, $post_id) {
    	$args['post_status'] = array('publish'); // WORKS FINE, displays only published posts, so the hook is right
    	//i thought $args['post__not_in'] will be set here through JS, but nothing is happening, plus i can't display $args in any way, die, print_r, even my custom function to catch variables and save them for displaying as notifications later in dashboard is not displaying ANYTHING. so i cant debug it (using 5.3 ACF)
    	return $args;
     }
    add_filter('acf/fields/post_object/query/key=field_592c54e17fea9', 'relationship_options_filter', 10, 3);

    Any idea how to pass post__not_in to acf/fields/post_object/query/?

  • The default $args that ACF sets and passes to your filter does not include this argument and ACF does not check for extra argument passed in the AJAX request. In your filter you need to check $_POST[‘post__not_in’], I think.

  • Yesterday I ended up passing var in acf.add_filter as a.exclude and retrieving it in acf/fields/post_object/query/ with $_REQUEST[‘exclude’].
    Thank you.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘JS prepare_for_ajax problem in acf_form’ is closed to new replies.