I try to keep user subscription in a metadata var.
The function is called by AJAX. Ahe AJAX is called but the metadata does not seem updated on frontend.
Here is the code:
jQuery
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#tags_list a').click(function(){
myid = $(this).parent("li").attr('id');
$.post(
'<?php echo admin_url( 'admin-ajax.php' ) ?>',
{
'action': 'change_subscription',
'type': 'post_tag',
'term_id': myid
},
function(response){
$('#'+myid).toggleClass('checked');
}
);
return false;
});
});
</script>
AJAX
add_action('wp_ajax_change_subscription', 'change_subscription');
function change_subscription() {
if (!empty($_POST['term_id']) && !empty($_POST['type'])) {
$user = wp_get_current_user();
update_user_meta( $user->ID, 'hannit_meta', 'My Value' );
die();
} else
die($st);
}
Front-end check:
<?php
$user = wp_get_current_user()->ID;
$tags = get_user_meta( $user->ID, 'hannit_meta', true);
echo "<!-- u:".$user." val ".$tags."-->";
?>
Result: <!-- u:236 val-->
What am I missing here?
First You can get rid of nasty globals in your AJAX call. I’m not sure what the
$st
variable that you were output is all about so I’ve excluded, but you can include as you wish –For testing, it looks like you were querying the meta incorrectly, so pleaes try this –
I was trying this exact method myself and was curious as to why your code wouldn’t work. I changed two things; it may be one or both of them that fixed it.
Firstly, you seem to be missing a bracket after your
else
in thechange_subscription
function. Secondly; I usually err on the side of caution and use the global$current_user
object:You also had an
$st
variable in your seconddie()
– I don’t know if this was defined elsewhere, but I omitted it for the sake of neatness. Depending on the strictness of your setup, an undefined variable may throw a spanner in the works.Anyway, using this exact code, this works perfectly for me. And thanks for the jumping-off point – I used your code as the basis for my own similar AJAX function.