Search code examples
wordpresswordpress-themingcustom-wordpress-pages

Overwrite wordpress theme page by plugin


I want to overwrite a theme page using my custom wordpress plugin , i tried to add filter but without result , i don't want to change directly on the theme because it's bad idea for every developer. this is my plugin code i added a filter to check pages

public function __construct(){
    add_filter('theme_file_path','customize_theme_pages', 99, 2 );
}

and i tried to replace theme page with my custom page like that

public function customize_theme_pages($path, $file = ''){
        if( 'woocommerce/checkout--/form-checkout.php' === $file ) {
            return plugin_dir_url( __FILE__ ).'inc/form-checkout.php';
        }
        return $path;
}

it seems logical solution for me , but there is no changes in my site


Solution

  • You can use the woocommerce_locate_template filter to override a woocommerce template file from your plugin.

    A quick example, assuming you want to override checkout/form-checkout.php with your plugin's inc/checkout/form-checkout.php file:

    function customize_theme_pages($template, $template_name, $template_path) {
        if ($template_name == 'checkout/form-checkout.php') {
            $template = plugin_dir_path( __FILE__ ) . 'inc/checkout/form-checkout.php';
        }
        return $template;
    }
    
    add_filter('woocommerce_locate_template', 'customize_theme_pages', 99, 3);
    

    **I have tested above code, and it's working on WooCommerce Version 3.5.0 running on WordPress 4.9.8.

    If you want you replace a standard page template, you can use page_template filter.