我正在尝试学习PHP和WP开发。我的目标是标记完成/阅读按钮单击。我发现这个很棒的Ajax教程插件。这是教程和插件的链接。我已经成功地设法编辑了我的需求。在单击时,它会检查数组中是否已经存在ID,是否是从数组中删除该元素。如果数组中没有ID,或者数组为空,则将帖子ID添加到数组中。之后,将数组更新为dB。
这是按钮的代码,它是在帖子内容之后添加的:
public function rml_button( $content ) {
$rml_post_id = get_the_id();
// Show read me later link only when user is logged in
if( is_user_logged_in() && get_post_type() == post ) {
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
$html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">DONE</a>';
$content .= $html;
}
else {
$html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">MARK AS DONE</a>';
$content .= $html;
}
}
else {
$html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">MARK AS DONE</a>';
$content .= $html;
}
}
return $content;
}
这是更新DB的代码:
public function read_me_later() {
check_ajax_referer( 'rml-nonce', 'security' );
$rml_post_id = $_POST['post_id'];
$echo = array();
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
foreach (array_keys($value, $rml_post_id, true) as $key) {
unset($value[$key]);
}
$echo = $value;
}
else {
$echo = $value;
array_push( $echo, $rml_post_id );
}
}
else {
$echo = array( $rml_post_id );
}
update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
// Always die in functions echoing Ajax content
die();
}
最后,这是ajax调用的.js:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});
我不知道的东西,对不起,如果这是一个愚蠢的问题,是如何在Ajax之后更改按钮文本?从"标记为完成"到"完成",反之亦然。如何调用此函数rml_button((,read_me_later((内部,以便在DB更新后更改该按钮文本。
谢谢。
在ajax success
函数中添加了if else statements
,以便能够将a tag
的文本从MARK AS DONE
更改为DONE
,反之亦然。
尝试:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
var ts = jQuery(this);
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
if(ts.html()=="DONE") { ts.html("MARK AS DONE"); } // ts.html()=="DONE" - maybe changed based on response
else { ts.html("DONE"); }
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});