Search code examples
phpjquerywordpresswordpress-theming

Wordpress theme options - wp_localize_script();


I'm using wp_localize_script(); to alter the JS in a theme I'm building, like so:

   wp_enqueue_script('custom', get_bloginfo('template_directory') . '/js/script.js');
   $settings = get_option('bro_options');
   wp_localize_script('custom','settings',$settings);

While this is good, the way this works is it writes inline JS right before the JS file in question loads, that way you can use certain variables to modify the JS and how it functions.

Problem is, I don't really like this option and how it outputs inline JS. Does anyone know of an alternative to this? I'm pretty sure this isn't how everyone does this with their theme options so there must be another way.

Any help whatsoever would be appreciated, please no links to plugins either.

In short: I'm looking for an alternative to using wp_localize_script(); or a better way of using it.


Solution

  • What I did was create a file called settings.js.php and in that I included the wp-config.php file.

    Like so:

    <?php
    
        header("Content-type: application/x-javascript");
    
        $c = 0;
    
        while($exists !== true && $notfound !== true) {
    
            $c++;
            $str = $str . '../';
    
            if(file_exists($str.'wp-config.php')) {
                $exists = true;
                include($str.'wp-config.php');
    
                $i = 0;
                $amount = sizeof($bro);
    
                echo 'var settings={';
                foreach($bro as $key => $value) {
                    $i++;
                    if($i<$amount) {
                        echo $key . ':"' . $value . '",';
                    } else {
                        echo $key . ':"' . $value . '"';
                    }
                }
                echo '};';
    
            }
    
            if($c === 20) { 
                $notfound = true;
            }
    
        }
    
    ?>
    

    Which would output my options in a variable like this:

    var settings = {
        foo: true,
        bar: false
    };
    

    I would enqueue this file before my custom.js file that way I could determine if some settings were on and off.

    if(settings.foo === true) {
        ...
    }
    

    All this so I don't have inline JS, there may be some cache issues but I'd rather have that than it output all options inline.