Kasse nur zulassen, wenn sich ein Produkt einer obligatorischen Kategorie im Warenkorb befindet

Ich möchte Kunden davon abhalten, zur Kasse zu gelangen, wenn sie keine bestimmte Produktkategorie in ihrem Warenkorb haben. Ich möchte ihnen auch mit einer Fehlermeldung mitteilen, dass sie ein bestimmtes Produkt hinzufügen müssen. Ich habe einen Code gefunden, kann ihn aber nicht ausführen. Ich habe es als Code-Snippet in meine Wordpress-Installation eingefügt, aber leider funktioniert es nicht und es werden keine Fehlermeldungen angezeigt, obwohl das Debuggen aktiviert ist. Hier ist der Code, den ich in Github gefunden habe und der möglicherweise geändert werden muss, damit dies funktioniert:

function sv_wc_prevent_checkout_for_category() {

    // set the slug of the category for which we disallow checkout
    $category = 'sibling';

    // get the product category
    $product_cat = get_term_by( 'slug', $category, 'product_cat' );

    // sanity check to prevent fatals if the term doesn't exist
    if ( is_wp_error( $product_cat ) ) {
        return;
    }

    $category_name = '<a href="' . get_term_link( $category, 'product_cat' ) . '">' . $product_cat->name . '</a>';

    // check if this category is the only thing in the cart
    if ( sv_wc_is_category_alone_in_cart( $category ) ) {

        // render a notice to explain why checkout is blocked
        wc_add_notice( sprintf( 'Hi there! Looks like your cart only contains products from the %1$s category &ndash; you must purchase a product from another category to check out.', $category_name ), 'error' );
    }
}
add_action( 'woocommerce_check_cart_items', 'sv_wc_prevent_checkout_for_category' );

/**
 * Checks if a cart contains exclusively products in a given category
 * 
 * @param string $category the slug of the product category
 * @return bool - true if the cart only contains the given category
 */
function sv_wc_is_category_alone_in_cart( $category ) {

    // check each cart item for our category
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        // if a product is not in our category, bail out since we know the category is not alone
        if ( ! has_term( $category, 'product_cat', $cart_item['data']->id ) ) {
            return false;
        }
    }

    // if we're here, all items in the cart are in our category
    return true;
}

So suche ich, um die Kasse zu stoppen (mit Fehlermeldung), wenn die Kategorie "Geschwister" der einzige Artikel im Warenkorb ist. Ich habe eine 'Standard'-Kategorie, die sich im Warenkorb befinden muss, bevor der Kunde zur Kasse kommt. Hoffe das macht Sinn.

Antworten auf die Frage(4)

Ihre Antwort auf die Frage