WordPress/Woocommerce lessons and adding new features

WordPress/Woocommerce lessons and adding new features

In WooCommerce 10.1.2 (I haven’t tested in other versions), WC_Product_* classes and WC_Order* classes can be expanded and effectively replaced.

A filter, woocommerce_product_classis applied to line 73 of the WooCommerce plugin includes/class-wc-product-factory.php file. The filter has an initial class name (which it gets from the product type), the product type, a context string (which indicates whether it is a full product or just a variant), and a product ID.

Replacing them is as simple as writing your replacement class and then connecting the filter to exchange the class names. My_Product_Simple below uses the extension purely for convenience.

class My_Product_Simple extends WC_Product_Simple {
    public string $vendor;
    // getters and setters if desired...
}
add_filter('woocommerce_product_class', function (
    string $classname,
    string $product_type,
    string $context,
    int $product_id = NULL,
): string {
    $thisClass = My_Product_Simple::class;
    $baseClass = WC_Product_Simple::class;

    $replacements = [
        WC_Product_Simple::class => $thisClass,
        // ...other known replacements
    ];

    if (array_key_exists($classname, $replacements)) {
        return $replacements[$classname];
    }

    // error handling...

    if (is_a($classname, $baseClass, TRUE) throw new Exception(
        "Running 'woocommerce_product_class' filter on "
        . "'$classname' is unexpected. In "
        . "\$replacements, map it to '$thisClass' "
        . "or itself or another appropriate class."
    );
    else throw new Error(
        "Ran 'woocommerce_product_class' filter on '$classname', "
        . "which does not extend '$baseClass'. "
        . "If needed, add it and its appropriate "
        . "replacement to the map in \$replacements."
    );
}, 1, 3);

Extend WC_Order works the same way, using the filter woocommerce_order_class. See rule 286 of class-wc-order-factory.php (in the same folder as the Product Factory class) for more documentation.

#WordpressWoocommerce #lessons #adding #features

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *