I want to pass my plugin a folder where it can access files, so I can run multiple instances with different folders set. Adding an attribute with the folder name was my first thought.
Because I'm using AJAX I need to access always the attribute of my shortcode. I've found this solution with passing the attribute to the JS and then pass it back when a AJAX call happens: https://wordpress.stackexchange.com/a/184219
I tried it, but it didn't worked. Is there maybe a more elegant way to do this?
Here is the important part of my PHP file:
add_action('init', 'wporg_shortcodes_init');
add_action('wp_enqueue_scripts', 'wporg_enqueue_scripts');
// My global variable for all AJAX processing PHP functions
$scrDir = "";
function wporg_shortcodes_init() {
add_shortcode('wporg', 'wporg_shortcode');
}
function wporg_shortcode($atts = [], $content = null) {
global $srcDir;
$srcDir = $atts['srcdir']; // Here is the attribute set
return '<h1>Hello World</h1>';
}
function wporg_enqueue_scripts() {
global $srcDir; // Needs to get right context with 'global'
wp_register_script('ajaxHandle', plugin_dir_url(__FILE__) . 'js/main.js', array(), false, true);
wp_enqueue_script('ajaxHandle');
wp_localize_script('ajaxHandle', 'ajax_object',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'srcdir' => $srcDir));
}
This is my AJAX call from main.js, which passes the attribute back:
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
data:{
action: 'search_for_files',
data: 'Test data',
srcdir: ajax_object.srcdir // Pass attribute back
},
success: function(data) {
console.log("srcdir: " + ajax_object.srcdir); // srcdir is empty although I've set it in wporg_shortcode()
},
dataType: "json"
});
And here is the shortshode:
[wporg srcdir="myDirectory"]
The problem is that my Javascript always returns an empty srcdir. What is wrong here?
Edit: The search expression in search_for_files
with exec
looks like this:
"find " . UPLOAD_FILES_PATH . $srcDir . " -iname '*" . $filename . "*' -type f";
../../..
as the directory value? Also, shortcode attributes come from the content, and only the content. Additionally, there's no code in your question for thesearch_for_files
ajax action, can you edit your question to include it?search_for_files
function searches withexec
with the find shell command for a file named in data. I will add the search expression in my question.