Skip to content

Instantly share code, notes, and snippets.

@mycred
Created July 27, 2018 11:31
Show Gist options
  • Save mycred/2a7c2d9ae232dcb8adb7c84f1e8ada3d to your computer and use it in GitHub Desktop.
Save mycred/2a7c2d9ae232dcb8adb7c84f1e8ada3d to your computer and use it in GitHub Desktop.
This script will award myCRED Points when a "Post" is published in WordPress. To define which tags gives points, the amount must be saved in the tags description field.
/**
* Award myCRED Points based on Tags
* This script will award points when a post is published based on
* what tags a post has. The amount is defined in the post tag description field.
* Requires myCRED 1.4 or higher!
* @version 1.1
*/
add_action( 'transition_post_status', 'mycred_pro_points_by_post_tags', 10, 3 );
function mycred_pro_points_by_post_tags( $new_status, $old_status, $post ) {
// Make sure myCRED is installed
if ( ! function_exists( 'mycred' ) ) return;
// Only award points when a "Post" gets published
if ( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post' ) {
// Load myCRED
$mycred = mycred();
// If the post author is excluded from using myCRED, leave now
if ( $mycred->exclude_user( $post->post_author ) ) return;
// Get all the tags that are connected to this post
$tags = wp_get_object_terms( $post->ID, 'post_tag' );
// If there are tags
$total = 0;
$tags_used = array();
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
// loop though tags
foreach ( $tags as $tag ) {
// Value should be stored in description
if ( empty( $tag->description ) ) continue;
// A value is set, add this up
$total = $total + $tag->description;
// Save the id of this tag for the log
$tags_used[] = $tag->term_id;
}
}
// No need to continue if no tags with points were found
if ( $total == 0 ) return;
// Make sure value is formated for myCRED
$total = $mycred->number( $total );
// Make sure points are only awarded once
if ( $mycred->has_entry( 'publishing_content', $post->ID, $post->post_author ) ) return;
// Award points
$mycred->add_creds(
'publishing_content',
$post->post_author,
$total,
'Points for published post',
$post->ID,
array(
'ref_type' => 'post',
'tags' => implode( ',', $tags_used )
)
);
}
}
@dcyflm
Copy link

dcyflm commented Apr 30, 2020

Great script! It's exactly what I was looking for! I'm using it for a custom post type.

Because I need the tag description for my tag archive page, it would be great if I could tweak the script in a way that the value does not come from the tag description, but instead from an ACF custom field (award_points) that Is attached to the tag.

Ideally, I would use something like this:

// Value should be stored in custom field
if ( empty( $tag->award_points ) ) continue;

// A value is set, add this up
$total = $total + $tag->award_points;

Maybe it's a stupid question. I'm not a developer... ;-)

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