我正在为我的网站构建一个插件,它在自定义元框中具有一个复选框,当未选中该复选框时,将显示Button1,如果选中,则将显示button2。那是给作者的。因此,我在每个帖子的帖子列表上都有一个按钮。因此,对于ajax,我想选中单击我在带有自定义列的帖子列表上创建的按钮时所对应的复选框,并将帖子元也从未选中状态更新为选中状态。
function cruiser_topic_pick_box_callback( $post ) {
$meta = get_post_meta( $post->ID );
$topic_checkbox_value = ( isset( $meta['topic_checkbox_value'][0] ) && '1' === $meta['topic_checkbox_value'][0] ) ? 1 : 0;
wp_nonce_field( 'topic_checkbox_value', 'topic_checkbox_value' );
echo'<input type="checkbox" name="topic_checkbox_value" id="topic_checkbox_value-' . $post->ID . '" value="1" ' . checked( $topic_checkbox_value, 1 ) . ' style="display: none;"/>'
if( $topic_checkbox_value == 0){
echo '<button class="btn btn-sm btn-info" id="click-btn" onclick="checkedFunction(' . $post->ID .')">Pick</button>';
}
else {
echo '<button class="btn btn-sm btn-warning">Picked</button>';
}
}
function cruiser_save_topic_writer( $post_id )
{
$topic_checkbox_value = ( isset( $_POST['topic_checkbox_value'] ) && '1' === $_POST['topic_checkbox_value'] ) ? 1 : 0;
update_post_meta( $post_id, 'topic_checkbox_value', esc_attr( $topic_checkbox_value ) );
}
因此,它已经在帖子内部运行,但是自定义列上的帖子外面有按钮。因此,当用户单击自定义列上的按钮时,它将自动更改要选中的复选框。默认情况下,该复选框为未选中状态。
我真正想要的是,当用户单击自定义列上的按钮时,该复选框将在帖子内被选中,结果Button1的文本将更改为button2。
答案 0 :(得分:0)
jQuery(document).ready( function(){
jQuery('#content').on('click', '.mycheckbox', function(e) {
e.preventDefault();
var post_id = jQuery(this).data( 'id' );
var mycheckbox_id = jQuery(this).val();
jQuery.ajax({
url : ajaxurl,
type : 'post',
data : {
action : 'update_post_topic_writer',
post_id : post_id,
mycheckbox_id : mycheckbox_id
},
success : function( response ) {
console.log(response);
}
});
});
});
PHP
add_action( 'wp_ajax_nopriv_update_post_topic_writer', 'update_post_topic_writer' );
add_action( 'wp_ajax_update_post_topic_writer', 'update_post_topic_writer' );
function update_post_topic_writer() {
if ( isset($_POST) ) {
$mycheckbox_id = $_POST['mycheckbox_id'];
$post_id = $_POST['post_id'];
update_post_meta( $post_id, 'topic_checkbox_value', esc_attr( $mycheckbox_id ) );
$return = array(
'message' => __( 'Saved', 'textdomain' ),
);
wp_send_json_success( $return );
}