Hook on trash post

admin2025-06-05  3

I want to perform an action when I delete one of my custom post types, which hook should I use:

wp_trash_mycpt

or

trash_mycpt

My action should run solely when mycpt is in the 'publish', 'draft' or 'future' state and moves towards the 'trash' state. When it is removed from trash itself there is no reason to run the function again.

I want to perform an action when I delete one of my custom post types, which hook should I use:

wp_trash_mycpt

or

trash_mycpt

My action should run solely when mycpt is in the 'publish', 'draft' or 'future' state and moves towards the 'trash' state. When it is removed from trash itself there is no reason to run the function again.

Share Improve this question edited Dec 12, 2018 at 13:26 Bharat Mane 1055 bronze badges asked Mar 15, 2013 at 15:31 urok93urok93 4,05412 gold badges67 silver badges104 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

The wp_trash_post hook might be what you're looking for:

Fires before a post is sent to the trash.

Also, there's the trashed_post hook:

Fires after a post is sent to the trash.

Here's some untested code to get you started:

function my_wp_trash_post( $post_id ) {

    $post_type = get_post_type( $post_id );
    $post_status = get_post_status( $post_id );
    if ( $post_type == 'mycpt' && in_array(
        $post_status, array( 'publish','draft','future' )
    )) {
        // do your stuff
    }
}
add_action( 'wp_trash_post', 'my_wp_trash_post' );

Run your function when post status changes from any of publish, draft or future to trash.

<?php
function my_function() {
    global $post;
    if('my_post_type' == $post->post_type) {
        // do your stuff here
    }
}

add_action('publish_to_trash', 'my_function');
add_action('draft_to_trash',   'my_function');
add_action('future_to_trash',  'my_function');

More info: Post Status Transitions

There is a wp_trash_post action that is called, but the post_status is changed to trash beforehand, meaning you would not be able to check whether the Post was published, etc.

EDIT I stand corrected, the post_status is changed to trash AFTER the action is called.

This should get you started however -

add_action('wp_trash_post', 'my_wp_trash_post')
function my_wp_trash_post(){

    if($post->post_type === 'mycpt') :
        // Do what ever you need to do here
    endif;

}

If it is of any use, there is also an delete_post action. For more information, see the Action Reference for delete_posts.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749105904a316411.html

最新回复(0)