How to manipulate the WooCommerce order key by removing the "wc_" prefix?

Viewed 304

I would like to manipulate the order key by removing wc_ from it. Problem is, no matter what I do, wc_ is not removed.

Is there any way to do this?

add_filter( 'woocommerce_generate_order_key', 'woocommerce_generate_custom_order_key', 10, 1 );
function woocommerce_generate_custom_order_key($order_key){
$order_key = str_replace( 'wc_', '', $order_key );
return $order_key;
}
1 Answers

The _order_key (Order Key) and post_id (Order ID) fields are different.

  • The order number you see in the WooCommerce backend is the post_id field of the wp_posts table of the Wordpress database.
  • The order key instead refers to the _order_key (meta_key) field of the wp_postmeta table of the Wordpress database.

The woocommerce_generate_order_key filter is documented here and as you can see you cannot use it to remove the wc_ prefix from the _order_key field of the order. Here is the extract of the source code:

/**
 * Generate an order key with prefix.
 *
 * @since 3.5.4
 * @param string $key Order key without a prefix. By default generates a 13 digit secret.
 * @return string The order key.
 */
function wc_generate_order_key( $key = '' ) {
    if ( '' === $key ) {
        $key = wp_generate_password( 13, false );
    }

    return 'wc_' . apply_filters( 'woocommerce_generate_order_key', 'order_' . $key );
}

If you want to manipulate the WooCommerce order key you have to use the set_order_key() method of the WC_Order class. Here you find the documentation.

You will also need to update the order post_password field in the wp_posts table.

So, for example, if you wanted to set a custom order key (removing the wc_ prefix) for each new order you could use this function:

// removes the "wc_" prefix from the WooCommerce order key field for each new order
add_action( 'woocommerce_new_order', 'set_custom_order_key', 99, 2 );
function set_custom_order_key( $order_id, $order ) {

    // get the order object
    $order = wc_get_order( $order_id );
    // gets the current order key
    $order_key = $order->get_order_key();
    // remove the "wc_" prefix
    $new_order_key = str_replace( 'wc_', '', $order_key );

    // updates the "_order_key" field of the "wp_postmeta" table
    $order->set_order_key( $new_order_key );
    $order->save();

    // updates the "post_password" field of the "wp_posts" table
    $post = get_post( $order_id );
    $post->post_password = $new_order_key;
    wp_update_post( $post );

}

The code has been tested and works. Add it to your active theme's functions.php.

If you want to manipulate the WooCommerce order id you have to use the woocommerce_order_number filter. The documentation can be found here.

You can find some examples here:

Related