WordPress.org

Ready to get started?Download WordPress

Forums

Custom Post Type Hooks (3 posts)

  1. eyeofbuddha
    Member
    Posted 4 years ago #

    Hi, I've been looking through the forum and internet for a while but couldn't really find the informations which could helo me, hope you guys can help me out.

    I am looking to hook actions on publishing and deleting posts custom post type, as I know there are ways to use hooks customized to custom post type (e.g 'publish_my-custom-post-type').

    add_action('publish_my-custom-post-type', 'my-function-on-publish');
    Works well with the publish action.

    My problem is actually with the delete action, as :

    add_action('delete_my-custom-post-type', 'my-function-on-delete'); doesn't work, neither does:

    add_action('delete_post', 'my-function-on-delete');
    function my-function-on-delete() {
    
    	if ($post->post_type == 'my-custom-post-type') {
            //My function
           }
    }

    I genuinely hope the solution isn't ridiculously obvious and that I am not wasting anyone time ( I am not really a wordpress guru...) but have spent a good few hours without being able to find a solution.

    Thanks a lot for any suggestion!

  2. Evan Anderson
    Member
    Posted 3 years ago #

    You're on the right track, the first hook you're using to publish your custom post type is {$new_status}_{$post->post_type} see {$new_status}_{$post->post_type} which relies on the first argument to be a status (draft, publish, new, etc...), however there is no delete status, and custom post types still get deleted with the delete_post function.

    Here is the delete_post hook in its habitat: delete_post. So as I mentioned you were on the right track, but you're attempting to use $post when its a null variable/object still. Your code should look something like:

    add_action('delete_post', 'my-function-on-delete');
    function my-function-on-delete($post_id) {
        $post = get_post($post_id);
        if ($post->post_type == 'my-custom-post-type') {
            //My function
           }
    }

    By default action hooks expect the first argument to be passed.

  3. amuralikumar
    Member
    Posted 3 years ago #

    Thanks ejdanderson, it works :)

Topic Closed

This topic has been closed to new replies.

About this Topic