我想给我的插件传递一个可以访问文件的文件夹,这样我就可以运行多个设置了不同文件夹的实例。我的第一个想法是用文件夹名添加一个属性。
因为我使用的是AJAX,所以我需要始终访问我的短代码的属性。我找到了这样一种解决方案,将属性传递给JS,然后在发生AJAX调用时将其传回:https://wordpress.stackexchange.com/a/184219
我试过了,但没用。有没有更优雅的方法?
以下是我的PHP文件的重要部分:
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));
}
这是我从main发出的AJAX调用。js,它将属性传回:$.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"
});
下面是shortshode:[wporg srcdir="myDirectory"]
问题是我的Javascript总是返回一个空的srcdir。这里怎么了?编辑:中的搜索表达式search_for_files
具有exec
如下所示:
"find " . UPLOAD_FILES_PATH . $srcDir . " -iname \'*" . $filename . "*\' -type f";