Skip to content

Instantly share code, notes, and snippets.

@gabrielmerovingi
Last active November 7, 2020 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrielmerovingi/477dcb17aee239e1a786 to your computer and use it in GitHub Desktop.
Save gabrielmerovingi/477dcb17aee239e1a786 to your computer and use it in GitHub Desktop.
Award points for users who subscribe or unsubscribe from your YouTube Chanel using myCRED.
/**
* Insert YouTube Subscription Listening Script
*/
add_action( 'wp_head', 'mycred_insert_youtube_script' );
function mycred_insert_youtube_script() {
if ( ! is_user_logged_in() ) return;
$token = wp_create_nonce( 'mycred-youtube-sub' );
?>
<script type="text/javascript">
function mycredyoutubesub( payload ) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open( "GET", "<?php echo admin_url( 'admin-ajax.php?action=mycred-youtube-subscribe' ); ?>&token=<?php echo $token; ?>&event=" + payload.eventType, true );
xmlhttp.send();
}
</script>
<?php
}
/**
* YouTube Subscribe / Unsubscribe AJAX Call Handler
*/
add_action( 'wp_ajax_mycred-youtube-subscribe', 'mycred_youtube_subscribe_unsubscribe' );
function mycred_youtube_subscribe_unsubscribe() {
// Security
check_ajax_referer( 'mycred-youtube-sub', 'token' );
$event = $_GET['event'];
$user_id = get_current_user_id();
// Required
if ( ! function_exists( 'mycred' ) || ! in_array( $event, array( 'subscribe', 'unsubscribe' ) ) ) wp_send_json_error();
// Load myCRED
$mycred = mycred();
// Check for exlusion
if ( $mycred->exclude_user( $user_id ) ) wp_send_json_error();
// Subscription = give points
if ( $event == 'subscribe' ) {
// Give 10 points
$mycred->add_creds(
'youtube_subscription',
$user_id,
10,
'%plural% for subscribing to our YouTube Channel'
);
}
// Unsubscribe = lose points
else {
// Take 10 points
$mycred->add_creds(
'youtube_subscription',
$user_id,
-10,
'Unsubscription from our YouTube Channel'
);
}
wp_send_json_success();
}
@TalonPower
Copy link

what "YouTube Subscription Listening Script" are you using here?

i could really uses this script.

what about comments?

@hammerheaddown
Copy link

any update to question above? i have similar needs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment