Search code examples
javascriptwordpresspluginscustomizer

How to open custom.php file in WordPress customizer without adding or registering the Page or Post in javascript


I am trying to customize the custom.php file in WordPress customizer. I am able to customize the file using PHP by using this hook template_include

add_filter( 'template_include', function( $return ) {
    if ( isset( $_GET['is_custom_page_active'] ) && true === $_GET['is_custom_page_active'] ) {
        return PLUGIN_DIR_PATH . 'templates/custom.php';
    }
    return $return;
} );

the above code is working properly.

Now I need to customize this file using javascript when I click on the registered panel open custom.php file

api.bind( 'ready', function() {
        wp.customize.panel( 'open-woocommerce-section', function( section ) {
            section.expanded.bind( function( isExpanding ) {
                if ( isExpanding ) {
                    let current_url = wp.customize.previewer.previewUrl();
                    current_url = current_url.includes( locaized_script.woocommerce_templates );
                    if ( ! current_url ) {
                       wp.customize.previewer.previewUrl.set(  locaized_script.woocommerce_templates );
                    }
                } else {
                    wp.customize.previewer.previewUrl.set( locaized_script.home_url );
                }
            } );
        } );
    } );
wp_enqueue_script( 'sa-enqueue-scripts', PLUGIN_URL . 'assets/js/custom.js', array( 'jquery', 'customize-preview' ), '1.0', true );
wp_localize_script( 'sa-enqueue-scripts', 'locaized_script', array( 'woocommerce_templates' => PLUGIN_URL . 'templates/custom.php', 'home_url' => home_url( '/' ) ) );

But this code is not working. Please help me to find the solution.

Thank you.


Solution

  • if ( is_customizer_preview() ) {
        add_filter( 'template_include', function( $template ) {
            if ( isset( $_GET['logic'] ) ) {
                return 'your-template';
            }
            return $template;
        } );
    }