我有一个wordpress应用程序,在一个页面中,我需要对某个自定义PHP文件进行AJAX调用。自定义PHP代码将创建一个图像文件并将其保存在目录中。在根目录下将图像存储在自定义目录中安全吗?
哪里是放置这个自定义PHP文件的好地方?我应该把它放在根目录下新创建的文件夹中吗?或者如果wordpress被更新,它会被删除吗?我需要为这个创建一个插件吗?
发布于 2016-12-14 03:55:05
最好是使用站点上传文件夹中的自定义目录来存储图像。创建它,然后chmod 775
将表单放在页面模板中。添加一个空的div与类“上传-响应”。在容器div关闭之前,插入一个脚本标记,它将回显admin-ajax.php路径到一个js变量:
<script>
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
</script>我使用jQuery来处理其余部分( upload.js文件的内容):
(function ($) {
$('body').on('click', '.upload-form .btn-upload', function(e){
e.preventDefault();
var imagedata = canvas.toDataURL('image/png');
var fd = new FormData();
//var files_data = imagedata;
fd.append('image', imagedata);
// our AJAX identifier
fd.append('action', 'my_upload_files');
// Remove this code if you do not want to associate your uploads to the current page.
//fd.append('post_id', <?php echo $post->ID; ?>);
$.ajax({
type: 'POST',
url: ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
$('.upload-response').html(response); // Append Server Response
}
});
});
})(jQuery);在插件文件中添加:
add_action('wp_enqueue_scripts','ajax_upload_script');
function ajax_upload_script() {
wp_enqueue_script('ajax-upload', plugins_url( '/js/upload.js' ), array('jquery'), '', true);
}
add_action('wp_ajax_my_upload_files', 'my_upload_files');
add_action('wp_ajax_nopriv_my_upload_files', 'my_upload_files'); // Allow front-end submission
function my_upload_files(){
//file handling here
}或者,如果您不想制作插件,请将这些操作添加到您的子主题functions.php,并将plugins_url( '/js/upload.js' )更改为get_stylesheet_directory_uri().'/js/upload.js'
发布于 2016-12-14 01:26:05
一种方法是使用像PHP职位代码这样的插件。这比将PHP硬编码成模板或WP页面要好。优点是您可以轻松地更新和更改代码,当需要对WP进行更新时,您不需要重新应用硬编码的PHP。
发布于 2016-12-14 04:13:37
If you want implement ajax in wordpress than you need use wp_ajax hook.
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add bellow code in function.php (theme folder)
javascript add in wp_footer hook on function.php
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
bellow wp_ajax hook add on function.php
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
// Don't forget to stop execution afterward.
wp_die();
}
Those code will not update when you update wordpress.
but if possible than add those code on function.php on child theme so in case if you want update theme than not update those code. https://stackoverflow.com/questions/41132872
复制相似问题