0

I'm building a plugin that will be introducing and managing/handling a new product type (like Simple, Variable, etc), and I want to also change the product_base permalink from product to that new product type, ie. property.

But in the sense of building a whole plugin to handle all that, I also want to change the default product_base array key stored in woocommerce_permalinks.

The problem is I'm not sure what's the best place to hook my code to... If I hook it in init it'll be executed on every page load, so that's a total waste of resources... What's the best place to hook it? My code isn't something exotic, just a simple:

 if( $permalinks = get_option( 'woocommerce_permalinks' ) ) {
    $permalinks['product_base'] = 'property';
    update_option( 'woocommerce_permalinks', $permalinks );
    flush_rewrite_rules();
 }

1 Answer 1

1

Use your plugin activation hook to make the change. That will only run once, when your plugin is first activated, allowing the user to overwrite that change later (if they want to).

register_activation_hook( __FILE__, function () {
    if ( $permalinks = get_option( 'woocommerce_permalinks' ) ) {
        $permalinks['product_base'] = 'property';
        update_option( 'woocommerce_permalinks', $permalinks );
        flush_rewrite_rules();
    }
});

If you want to always force the permalink settings, use the underlying WordPress hook pre_update_option_$option_name:

function wpse_406568_woocommerce_permalinks( $permalinks ) {
    $permalinks['product_base'] = 'property';

    return $permalinks;
}

add_filter( 'pre_update_option_woocommerce_permalinks', 'wpse_406568_woocommerce_permalinks' );

...that will always override whatever setting the user used for product base when saving their WC permalink settings.

1
  • register_activation_hook was indeed the place I was looking for... No need to force using the product_base I prefer... Thank you so much for your answer!
    – Faye D.
    Commented Jun 8, 2022 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.