1

I have the following function that deducts at point when a post is removed. But when I remove a page, the wp_trash_post is also called.

// Remove 1 point if their post get removed
function deletePointFromUser($post_id) {
$post = get_post($post_id);
$authorid = $post->post_author;
$currentQPointNumber = get_user_meta($authorid, 'points', true);
// Delete 1 to the current Point Score
update_user_meta($authorid, 'points', $currentQPointNumber-1); 
 }
add_action('wp_trash_post', 'deletePointFromUser');

Is there a way to restrict this function to only apply to posts and not pages?

5
  • 2
    After the get_post line, why not just do a check for $post->post_type === 'post', and if not, just return?
    – Shane
    Commented Mar 5, 2014 at 7:54
  • 1
    @Shane : post that as an answer, please, and provide the modified code.
    – s_ha_dum
    Commented Mar 5, 2014 at 14:50
  • post_type doesnt work here
    – dkl
    Commented Mar 5, 2014 at 14:59
  • I don't see why 'post_type' doesn't work here. dkl uses get_post() which will grab 'post_type' attribute from the post. Commented Mar 5, 2014 at 18:02
  • 1
    @s_ha_dum: Looks like Douglas.Sesar beat me to it :)
    – Shane
    Commented Mar 6, 2014 at 8:46

1 Answer 1

2

You could just add something like:

// Remove 1 point if their post get removed
function deletePointFromUser($post_id) {
  $post = get_post($post_id);

  if( $post->post_type != 'post' ) return;//added code

  $authorid = $post->post_author;
  $currentQPointNumber = get_user_meta($authorid, 'points', true);
  // Delete 1 to the current Point Score
  update_user_meta($authorid, 'points', $currentQPointNumber-1); 
}
add_action('wp_trash_post', 'deletePointFromUser');

Then your point subtraction will only occur if the $post is a post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.