Home > OS >  Empty woocommerce cart when visiting page under specific parent page
Empty woocommerce cart when visiting page under specific parent page

Time:11-07

How can I adjust this PHP code so that it empties the woocommerce cart when I visit a page under a specific parent page?

Example:

  1. I visit www.domain.com/anyparentpage/page

  2. nothing happens

  3. I visit www.domain.com/mtm-user/page

  4. empties cart

`

add_action( 'template_redirect', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    global $post;
    $slug = $post->post_name;
    if($slug == 'mtm-user') {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}

`

I tried adding $post->post_parent but it didnt work

CodePudding user response:

Try replacing slug with parent post id. here 31 is post parent id

add_action( 'template_redirect', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    global $post;
    $parent_id = $post->post_parent;
    if($parent_id == 31) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}
  • Related