• Resolved teeboy4real

    (@teeboy4real)


    Hi

    Please I need help getting this code to work, I want to empty user cart when logged in users delete a pending or inactive ad in the [adverts_manage] page

    function empty_cart_on_advert_delete($advert_id) {
        // Check if WooCommerce is active
        if (function_exists('WC')) {
            // Get the post object
             $advert = get_post($advert_id);
    
            // Check if the post type is 'post'
            if ($post && $post->post_type === 'advert') {
                // Check if the post status is 'draft' or 'pending'
                if (in_array($post->post_status, array('draft', 'wc_pending', 'pending'))) {
                    // Check if the user is logged in
                    if (is_user_logged_in()) {
                        // Get the current user ID
                        $user_id = get_current_user_id();
    
                        // Get WooCommerce cart instance
                        $cart = WC()->cart;
    
                        // Check if the user has items in the cart
                        if ($cart->is_empty()) {
                            return; // If cart is empty, do nothing
                        }
    
                        $cart->empty_cart(true);
                    }
                }
            }
        }
    }
    add_action('adverts_delete', 'empty_cart_on_advert_delete');

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Greg Winiarski

    (@gwin)

    Hi,

    do you have this code copied from somewhere (if so then where)?

    I do not think the “adverts_delete” action exists, so I am guessing this is not even being run anywhere.

    Thread Starter teeboy4real

    (@teeboy4real)

    Thanks for the feedback I view the text from the url link when I hovered over the delete button in the adverts manage page. I wasnt sure if the action (before_delete_post) would work

    Plugin Author Greg Winiarski

    (@gwin)

    Ohh ok, the adverts_delete is not a real action in terms of using the add_filter() and add_action() functions, you should rather use the before_delete_post or delete_post (both should work fine with Adverts).

    Note that there is also a bug in your snippet, the line

    $advert = get_post($advert_id);

    should be

    $post = get_post($advert_id);

    otherwise the “if” statement will never be executed.

    Thread Starter teeboy4real

    (@teeboy4real)

    Thank you Greg the code worked successfully. I am really grateful for your assistance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Empty cart on advert deletion’ is closed to new replies.