Невозможно локализовать скрипты в WordPress

#javascript #php #wordpress

#javascript #php #wordpress

Вопрос:

Цель состоит в том, чтобы получить путь к каталогу шаблонов в файле javascript, не ставя под угрозу стандарты WordPress. Вот мой functions.php файл

 <?php

add_action( 'admin_menu', 'register_options_page' );
add_action( 'admin_enqueue_scripts', 'my_scripts_method' ); 



function register_options_page()
{
    $my_hook = add_menu_page( 'Theme Options', 'Theme Options', 'manage_options', 'merry_options', 'get_theme_options', 'dashicons-share-alt', 99 );
    // var_dump($my_hook); die();
}

function my_scripts_method( $hook ) 
{
    if( 'toplevel_page_merry_options' !== $hook ) // Previously at: var_dump   die
        return;

    wp_enqueue_script( 'jquery-ui-tabs' );
    wp_enqueue_script( 'themeoptions-js', get_template_directory_uri().'/framework/themeoptions.js');
    wp_enqueue_style( 'themeoptions-style', get_template_directory_uri().'/framework/themeoptions.css');
    wp_enqueue_style( 'themeoptions-font-awesome-style', get_template_directory_uri().'/framework/styles/font-awesome.css');
    wp_enqueue_style( 'themeoptions-font-awesome-style-min', get_template_directory_uri().'/framework/styles/font-awesome.min.css');

    //Localizing scripts to get PHP code in return

    wp_register_script( 'merrypress-js-localized-scripts', get_template_directory_uri().'/framework/themeoptions.js');
    $translation_array = array( 'some_string' => get_template_directory_uri());
    wp_localize_script( 'get_template_directory_uri', 'localizedScriptObject', $translation_array );


    wp_enqueue_script( 'merrypress-js-localized-scripts' );

    # As best practice, the CSS AND JAVASCRIPT bellow should be enqueued here too
}

function get_theme_options()
{
    # Use THIS, not file_get_contents    
    include_once get_template_directory()."/framework/themeoptions.php";
}

?>
  

И вот код внутри themeoptions.js файл

 var gettemplatepath=some_string;

 alert(gettemplatepath) ; // alerts 'Some string to translate'


jQuery(document).ready(function($) {

        //main theme options tabs

        $( "#tabs" ).tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" );
        $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );





        //on click function
        $( "#theme-options-save-button" ).click(function() {

            $(".theme-options-savechanges-loader").show();
            var request=$.ajax({
                type: "POST",
                url: ".../commitchanges.php",
                data: { 

                    name: "John",
                    location: "Boston"

                    }
                    });
                    request.done(function( msg ) {
                        alert( "Data Saved: "   msg );
                        $(".theme-options-savechanges-loader").hide();
                        });

                        request.fail(function( msg ) {
                        alert( "Fail: "   msg );
                        $(".theme-options-savechanges-loader").hide();
                        });


            });       //end on click function 







        }); //end document.ready
  

Ошибка, которую я получаю в консоли разработчика:

Ошибка неперехваченной ссылки: some_string не определен

Вы можете помочь?

Комментарии:

1. @JoffreyMaheo Даже если я делаю localizedScriptObject.some_string , он все равно не работает.

2. wp_localize_script#Параметры

Ответ №1:

Локализованный скрипт можно использовать для предоставления любых данных вашему скрипту. Сценарий, который вы хотите локализовать, вероятно, ‘merrypress-js-localized-scripts’, а не ‘get_template_directory_uri’.

 wp_localize_script( 'merrypress-js-localized-scripts', 'localizedScriptObject', $translation_array );
  

Теперь откройте консоль и проверьте html, чтобы увидеть, что WordPress создал другой скрипт над ‘merrypress-js-localized-scripts’, который выглядит как:

 <script type="text/javascript">
/* <![CDATA[ */
var localizedScriptObject = {"some_string":"http://localhost/the_wall/wp-content/themes/twentyfourteen"};
/* ]]> */
</script>