Search code examples
phpwordpresswoocommercecustom-taxonomyproduct-variations

Adding postfix to WooCommerce product variation gets overwritten


Im beginning to expect that there is some "update function" built into WooCommerce that only lets me rename variations post_title for a little while. And then it gets set back to what the hooks / WooCommerce has decided?

I want to add postfixes like "(Cancelled)" to specific variations programatically.

$new_title = get_the_title( $variationid ) . ' (Cancelled)';
wp_update_post(array('ID' =>$variationid, 'post_title' => $new_title));

This only "hangs on" for a little while...

I tried disabling this hook, and then change the title, but still it gets overwritten.

add_filter( 'woocommerce_product_variation_title_include_attributes', '__return_false' );

Is there any way to get WooCommerce to stop overwriting titles of variations?

My solution based on @LoicTheAztec 's answer, using logic based on my custom post status "cancelled".

add_filter( 'woocommerce_product_variation_title', 'filter_product_variation_title_callback', 10, 4 );
function filter_product_variation_title_callback( $variation_title, $product, $title_base, $title_suffix ) {

    $id = $product->get_id();
    $status = get_post_status($id);
    if ($status == 'cancelled'){
        return $variation_title . ' (' . __("Cancelled", "woocommerce") . ')';
    } else {
        return $variation_title;
    }
}

Solution

  • You should try using dedicated woocommerce_product_variation_title filter hook that allows temporarily to alter product variation title (conditionally), this way:

    add_filter( 'woocommerce_product_variation_title', 'filter_product_variation_title_callback', 10, 4 );
    function filter_product_variation_title_callback( $variation_title, $product, $title_base, $title_suffix ) {
        // Conditional custom field (example)
        if( $product->get_meta('_is_cancelled')  )
            $title_base .= ' (' . __("cancelled", "woocommerce") . ')';
    
        return $title_base
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works.

    Note: The $variation_title returns the product title including product attributes, that is disabled in the function code above…


    On order edit pages (it is reflected too):

    enter image description here