I was making a plugin and I have a javascript file where I want to take some options saved in the database to show well the function.

So I have this:

function wp_home(){

    wp_enqueue_script( 'some-name-1', '//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js', '1.0.0', true );
    wp_enqueue_style( 'some-name-2', plugins_url( 'assets/jquery.something.css', __FILE__ ) );
    wp_enqueue_script( 'some-name-3', plugins_url( 'assets/jquery.something.js', __FILE__ ), '1.0.0', true );



        global $table_prefix;
        $dbh = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
        $table = $table_prefix.'options';
        $qd = "SELECT option_value FROM $table WHERE option_name="description"";

        $description = $dbh->get_results( $query_link );

        $description = $description[0]->option_value;

      //HERE I HAVE THE STRING OF $description AND I WANT TO PASS INSIDE TO CUSTOM-JS-PHP

     wp_enqueue_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ), '1.0.0', true );

}

The file custom-js.php it’s like this:

     <?php header("Content-type: text/javascript"); ?>


        $(document).ready(function(){
            $.showBox({
                message: '<?php echo $description; ?>',
            });
        });

How I can take the $description? If I put the javascript inside wp_home() it doesn’t work.

Thanks

2 Answers
2

You can use wp_localize_script() to pass php variables to javascript. You create an array in php and then pass it to the function as the third parameter. It will come through as an object you name with the second parameter.

First, register the script.

wp_register_script( 'custom-name-js', plugins_url( 'assets/custom-js.php', __FILE__ ) );

Second, build your array and run wp_localize.

$my_array = array( 'description' => $description[0]->option_value );
wp_localize_script( 'custom-name-js', 'js_object_name', $my_array );

Finally, you enqueue your script.

wp_enqueue_script( 'custom-name-js' );

Then, in your js file, you will have a js object available named js_object_name (or whatever you pass as the second parameter to wp_localize_script) with a property of description.

js_object_name.description

Leave a Reply

Your email address will not be published. Required fields are marked *