I'm trying to create a popup/modal notification if a logged-in user has reached a certain level.
I use the following code (simplified):
function theme_achievements() {
$value = user_total_posts( get_current_user_id() )
if( $value >= '0' && $value <= '499' ) {
update_user_meta( get_current_user_id(), 'author_level', array( 'lvl-1', '' ) );
} elseif( $value >= '500' && $value <= '999' ) {
update_user_meta( get_current_user_id(), 'author_level', array( 'lvl-2', '' ) );
} else {
...
}
}
add_action( 'wp_head', 'theme_achievements' );
Now I would like to create a popup/modal notification when the user reached a certain level. From here on out, I need some guidance. When a user clicks on the close icon, it should update the usermeta.
Updated
Added data-id
attribute that's needed for update_user_meta
function theme_notification_popup() {
$level = get_user_meta( $user_id, 'author_level', true ); ?>
<div id="my-id" class="uk-modal" data-uk-modal="{center:true}">
<div class="uk-modal-dialog">
<a class="uk-modal-close uk-close" data-id="<?php echo esc_attr( $level[0] ); ?>-notification-read"></a>
<h4>Title</h4></div>
...content...
</div>
</div>
<?php }
add_action ('wp_footer', 'theme_notification_popup');
Since AJAX is the way to handle this, here's my AJAX code
jQuery( 'document' ).ready( function( $ ) {
jQuery('#uk-modal').on('click', '.uk-modal-close', function(e) {
e.preventDefault();
var levelRead = $('.uk-modal-close').attr('data-id');
$.ajax( {
url : ajax_url,
type: 'POST',
data: {
action : 'km_ajax',
'data-id': levelRead,
}
} )
.success( function( results ) {
// console.log( 'User Meta Updated!' );
console.log( levelRead );
} )
.fail( function( data ) {
console.log( data.responseText );
console.log( 'Request failed: ' + data.statusText );
} );
return false;
});
} );
And here's the required callback
function km_ajax_callback() {
if( ! empty( $_POST['data-id'] ) ) :
$new_val = sanitize_text_field( $_POST['data-id'] );
update_user_meta( get_current_user_id(), 'km_user_meta_author_level', array( '', $new_val ) );
endif;
exit();
}
add_action( 'wp_ajax_nopriv_km_ajax', 'km_ajax_callback' );
add_action( 'wp_ajax_km_ajax', 'km_ajax_callback' );
In console I see the AJAX is succesful when a user clicks on the close
button. However, the second array of the user_meta doesn't get updated. This means there must be a mistake in my km_ajax_callback()
function.
Can anyone tell me what I'm doing wrong? Or what I'm missing?
theme_achievements()
function. This function overrides the ajax callback due to thewp_head
function. Anyone know of a better way?theme_achievements()
) doesn't really require the use of AJAX. I was hoping I could simply use a function.theme_achievements()
function and test the AJAX callback, then the user meta field gets updated just fine.