Unable to pass an available variable in an ajax hook into another hook
-
Hi,
I’m stucked for 4 days right now. I have created a little plugin in which one feature is the ability to change the upload folder. Everything is working as expected for already saved post since we can $_POST to retrieve the different values which makes the folder structure… but I want to cover people which uploads files in an unsaved post.
For this, I have created a JS file which retrieves the value of the title field each 5 seconds. This is processed by ajax btw, and the JS itself is working fine. The main problem I’m encoutering is that I’m unable to grab this value and put it into another hook : my upload filter.
Here are some details :
1 – My script
setInterval( function() { var title = $('#post-title-0').val(); jQuery.post( ajaxurl, { 'action': 'my_action', 'param': title }, function(response){ console.log(response); } ); }, 5000);
2 – I include a wp-localize script in order to be sure that ajax files will be available
function add_js_scripts() { // pass Ajax Url to script.js wp_localize_script('script', 'ajaxurl', admin_url( 'admin-ajax.php' ) ); } add_action('admin_enqueue_scripts', 'add_js_scripts');
3 – This is the related ajax hook
add_action( 'wp_ajax_my_action', 'my_action' ); function my_action() { $output=$_POST['param']; if($output){ print_r($output); } else{ echo ' error : ' . $output; } die; }
===> With all this, I’m able to grab the actual title value. But I’m nevertheless unable to pick this value in order to put it in my upload filter. It’s kinda like a scope issue : the jQuery is able to grab the proper data, the Ajax response is at 200:OK in my browser inspector, I can see the 2 values of “action” and “param”, but can’t get the ‘param’ value in my wp_handle_upload_prefilter/wp_handle_upload.
Here’s a simplified version of my wp_handle_upload_prefilter/wp_handle_upload filter :
function my_custom_upload_dir($path) { $mydir .= '/'.$_POST['param']; $path['subdir'] = $mydir.'/'; $path['path'] = $path['basedir'].$mydir; $path['url'] = $path['baseurl'].$mydir; return $path; } // Filters which handle the new directory add_filter('wp_handle_upload_prefilter', 'my_upload_prefilter'); add_filter('wp_handle_upload', 'my_handle_upload'); function my_upload_prefilter( $file ) { add_filter('upload_dir', 'my_custom_upload_dir'); return $file; } function my_handle_upload( $fileinfo ) { remove_filter('upload_dir', 'my_custom_upload_dir'); return $fileinfo; }
I really need some help, I’m stucked for too much time. Thanks in advance.
PS : I tried a JSON solution too, but doesn’t work too ?? I have created a proper route, but it returns an empty array inside the upload filter. I’m disapointed…
- The topic ‘Unable to pass an available variable in an ajax hook into another hook’ is closed to new replies.