如何创建一个按钮点击计数器的元框?

时间:2013-08-28 作者:Ari

我试图在自定义帖子类型中创建按钮点击计数器元框,但我无法使其工作。我想做的是,当用户单击submit按钮时,它就会update_post_meta 在后台,并通过以下方式在当前屏幕上显示值echo get_post_meta 使用ajax。

以下是我目前的代码:

Hooks the metabox function

add_action(\'add_meta_boxes\', \'add_custom_categories_box\');

Add metabox function

function add_custom_categories_box() {  
 add_meta_box(
        \'wpse_54822_sectionid\',
        __( \'Page Attachments\' ), 
        \'wpse_54822_inner_custom_box\',
        \'indtablea\', \'normal\'
    );
} 

Meta box

function wpse_54822_inner_custom_box(){
?>
<script>
jQuery(document).ready(function($){

$(\'#target\').click(function() {
    $(\'#output\').html(function(i, val) { return val*1+1 });
});

$(\'.submitmeplease\').on(\'click\', function(e){
e.preventDefault();
    $(\'#counter\').html(function(i, val) {
        $.post({
            url: ajaxurl,
            action:"ak_attach",
            type: \'POST\',
            data: {increment: true},
            success: function() { alert(\'Request has returned\') }
        });
        return +val+1;
});
});
});
</script>
<?php
?>
<button id="target" type="button">Click Me</button>
<div id="output">10</div>

<div id="#counter">1</div>
<input type="submit" name="submit" class="submitmeplease" value="Submit" />
<?php
}

Ajax Response

 // Response to ajax script
function ajaxResponse($post){  
$data = $_POST[\'submit\'];
update_post_meta($post_ID, \'my_key\', $data);
 }  
add_action(\'wp_ajax_ak_attach\', \'ajaxResponse\');
我搞不清楚变量的字符串是什么$dataajaxResponse 函数应为。

有人能告诉我如何在metabox中创建按钮点击计数器吗?

请帮帮我。。

3 个回复
SO网友:gmazzap

首先,像这样输出javascript是一种更糟糕的做法。因此,如果您创建javascript文件并使用wp_enqueue_script 钩住的admin_enqueue_scripts 行动

function enqueue_my_ajax( $hook ) {
    if( \'post.php\' != $hook && \'post-new.php\' != $hook ) return;
    // if you use in theme use get_template_directori_uri to retrieve the url
    wp_enqueue_script( \'my_ajax_script\', plugins_url(\'/my_ajax_script.js\', __FILE__) );
}
add_action( \'admin_enqueue_scripts\', \'enqueue_my_ajax\' );
其次,当您使用metabox和ajax时,最好使用nonces。您可以使用wp_nonce_field 在metabox中创建隐藏的nonce输入,并检索值并使用ajax发布。

登记入住Codex 有关上述函数的详细信息。

关于这个问题,post Id应该通过ajax传递,或者ajaxResponse 无法使用它。

因此,显示元数据库的功能应该是:

function wpse_54822_inner_custom_box( $post ) {
  $current_count = get_post_meta($post->ID, \'_increment_key\', true) ? : 1;
  wp_nonce_field( \'increment_my_count\', \'_nonce_count\' );
?>

<input type="hidden" id="_count" name="_count" value="<?php echo $current_count ? : 1; ?>" />
<input type="hidden" id="_postid" name="_postid" value="<?php echo $post->ID; ?>" />
<div id="counter"><?php printf( \'Current Count: %d\', $current_count ); ?></div>
<input type="button" name="button" class="button button-primary submitmeplease" value="<?php _e(\'Update\'); ?>" />

<?php } ?>
您的javascript(在如上所列的my\\u ajax\\u script.js文件中)应该是:

jQuery(document).ready(function($){
  $(\'.submitmeplease\').on(\'click\', function(e){
    e.preventDefault();
    var nonce = $(\'input[name="_nonce_count"]\').val();
    var count = $(\'#_count\').val();
    var id = $(\'#_postid\').val();
    $.ajax({
      url: ajaxurl,
      type: \'POST\',
      data: { _nonce_count: nonce, action: \'update_my_count\', _count: count, postid: id },
      success: function( data ) {
        if (data != \'\' && data != \'0\')
          $(\'#_count\').val( data );
          $(\'#counter\').html(\'Current Count: \' + data)
        }
    });
  });
});
您的myUpdateCount 功能应为:

function myUpdateCount() {
  if ( ! check_admin_referer( \'increment_my_count\', \'_nonce_count\' ) ) die();
  $postid = isset( $_POST[\'postid\'] ) && $_POST[\'postid\'] ? $_POST[\'postid\'] : null;
  if ( ! $postid ) die();
  if ( ! current_user_can(\'edit_posts\', $postid) ) die();
  $new_count = isset( $_POST[\'_count\'] ) && $_POST[\'_count\'] ? $_POST[\'_count\'] + 1 : 1;
  update_post_meta($postid, \'_increment_key\', $new_count);
  die( (string)$new_count );
}

add_action(\'wp_ajax_update_my_count\', \'myUpdateCount\');

SO网友:iEmanuele

WordPress中的ajax调用基本上如下所示:

The jQuery / JS script:

jQuery.ajax({
  url: ajaxurl, // the URL where the data are submitted
  type: \'POST\'  // the METHOD on how the data are submitted
  action: \'myaction\', // the ACTION called to process the data
  data: { // the DATA sent to the server 
    submit: \'somevalue\',
    postid: $(\'#postid\').val() // You can store the post ID value in an hidden input text field within the function you use to diplay the content of your metabox.
  },
  success: function(data){
    //Do something with the DATA pushed from server
    console.log( data );
  }
});

The server side

// functions.php
add_action( \'wp_ajax_myaction\', \'wpcf_process_data\' );
function wpcf_process_data(){

  //I\'m sending data via POST method so i look for this data in $_POST variable
  $submit = isset( $_POST[\'submit\'] ) ? $_POST[\'submit\'] : false;
  $postid =  isset( $_POST[\'postid\'] ) ? $_POST[\'postid\'] : false;   

  //Do something with the data, for example update post meta
  $update = update_post_meta( $postid, \'mykey\', $submit )

  //echo the result, in order to send it to the ajax call. we know that if update_post_meta creates a new record, it returns the meta_id, if you update a value, it returns true and false on failure. in other words this the data pushed from the server.
  echo $update;

  //Every ajax call must die.. i know sounds creepy, but it has to be done
  die();
}
希望有帮助。

SO网友:Ari

以下是我为实现它所做的!希望这对任何觉得有用的人都有帮助。这个例子在我的本地服务器上运行得很好。不过,我还没有为安全性创建nonce。因此,如果要在live站点上使用nonce,您需要找到如何添加它。

Meta Box Hook

add_action(\'add_meta_boxes\', \'add_custom_categories_box\');

function add_custom_categories_box() {  
 add_meta_box(
        \'wpse_54822_sectionid\',
        __( \'Page Attachments\' ), 
        \'wpse_54822_inner_custom_box\',
        \'indtablea\', \'normal\'
    );
}  

Metabox Form

function wpse_54822_inner_custom_box(){
global $post;
echo get_post_meta($post->ID, \'my_key\', true); // Show result

//You need to give your form fields class name or id to connect them with jQuery.    
?>
    <br/>
    <button id="target" type="button">Click Me</button>
    <input type="text" name="submit" class="submitme" value="" placeholder="columns" />
    <input type="text" name="posid" class="posid" value="<?php echo $post->ID; ?>" />
    <?php
    }

Register and Enqueue The jQuery To Administration Screen

我使用传统的方式将脚本包含到管理屏幕中。

function enqueue_my_ajax( $hook ) {

    wp_register_script( \'my_ajax_script\', plugins_url(\'/simpleajax/my_ajax_script.js\') );
    wp_enqueue_script(\'my_ajax_script\');
}
add_action( \'admin_enqueue_scripts\', \'enqueue_my_ajax\' );
function enqueue_my_ajax( $hook ) {

    wp_register_script( \'my_ajax_script\', plugins_url(\'/simpleajax/my_ajax_script.js\') );
    wp_enqueue_script(\'my_ajax_script\');
}
add_action( \'admin_enqueue_scripts\', \'enqueue_my_ajax\' );
jQuery Ajax这是my_ajax_script.js 文件

jQuery(document).ready(function($){

$(\'#target\').click(function(e) {
    var m = $(\'.submitme\').val(); //get value of input field with class name "submitme"
    var pid = $(\'.posid\').val(); //get value of input field with class name "posid"
    var sbmit = $(\'.submitme\').val();
    $(\'.submitme\').val(m*1+1); // Increment the input field\'s value named "submitme"        
    var data = {
        action: \'my_action\', // Put this action name after wp_ajax hook  
        whatever: 1234,
        postid: pid, // get the post id to included in update_post_meta
        submit: sbmit // get the value to be submitted.
    };

    $.post(ajaxurl, data, function(response) { // do the ajax
//Display the success response here if you want to do it!
    });
});

});

Useful External Referrences:

Wordpress插件中的Ajaxhttp://codex.wordpress.org/AJAX_in_Plugins

jQUeryajax API文档http://api.jquery.com/jQuery.ajax/

jQuery API文档http://api.jquery.com/

结束

相关推荐

为wp_ajax_添加回调函数不起作用

我试图在WordPress AJAX操作中再添加一个回调函数woocommerce_apply_coupon.这个动作是在WooCommerce插件中定义的,我想从插件文件中向这个动作添加我自己的回调函数。我所尝试的:add_action( \'wp_ajax_nopriv_woocommerce_apply_coupon\',\'darn\',999); add_action( \'wp_ajax_woocommerce_apply_coupon\', \'darn\',999); &#