我想使用transient作为我的小部件。用户可以选择缓存数据的时间(1、2、10小时)。我还想在小部件表单中添加一个按钮Refresh now。
我不知道如何在点击时调用delete_transient。
我正在考虑创建一些隐藏的输入()。如果单击按钮,则设置1。在function widget()中检查它,如果需要的话调用delete_transient。但我认为不能将0设置为refresh-data内部的widget函数。
发布于 2019-02-14 20:58:26
我假设小部件和“刷新现在”按钮显示在前端,是吗?删除暂存的一个选项是使用ajax来完成它。
这是一个相当粗糙的例子,但我希望它能让你知道该怎么做。您可以在WordPress中从法典中了解更多关于Ajax的内容。
// In your php file
add_action( 'wp_ajax_my_delete_transient_action', 'my_delete_transient_action' );
add_action( 'wp_ajax_nopriv_my_delete_transient_action', 'my_delete_transient_action' ); // for users that are not logged in
function my_delete_transient_action() {
// Check nonce and other stuff here as needed
// If and when everything is ok, then use the delete_transient function
$deleted = delete_transient('my_user_specific_transient'); // returns bool
// Option 1 to send custom text response back to front-end
if ($deleted) {
echo 'Transient deleted';
} else {
echo 'Transient deletion failed';
}
die();
// Option 2
if ($deleted) {
wp_send_json_success('Transient deleted');
} else {
wp_send_json_error('Transient deletion failed');
}
}
// In your js file
jQuery(document).ready(function($) {
$('.my-reset-button').on('click',function(event){
event.preventDefault();
var data = {
'action': 'my_delete_transient_action',
};
// You can use wp_localize_script in php file to have admin_url( 'admin-ajax.php' ) available in front-end
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response); // do something with the response
});
});
});https://wordpress.stackexchange.com/questions/328740
复制相似问题