0

After updating my loop to get everything I want with this code:

<?php
$json = "";
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        global $wpdb;
        $query = "SELECT * FROM ". $wpdb->prefix ."options WHERE option_id = 1";
        $results = $wpdb->get_results($query);
        if ($results){
            $json .= json_encode($results);
        }
    }
}
echo $json;
?>

I want to use the $json on the main page with js but I dont know how to get the variable.

Thank you in advace!

6
  • Are you running this on a page or a post? What values are being retrieved for which you need to manually write an SQL query for? Commented Apr 14, 2021 at 22:00
  • this script is ran in the index.php loop. I retrieve the database products to get them into a js function in the functions.php file. Commented Apr 14, 2021 at 22:05
  • Are the products a custom post type? Commented Apr 14, 2021 at 22:06
  • I dont know what that means, they are from woocomerence. Sry but I am a beginer. Commented Apr 14, 2021 at 22:08
  • That's okay. Custom post types are, like the name suggests, types of posts (pages, posts, comments, products) which are non-standard to WordPress. Like created by you or me in our theme, or by a plugin. WooCommerce products are also a post type. My question now is, are you trying to get the products from WooCommerce so you can use them in your JavaScript file? Commented Apr 14, 2021 at 22:12

1 Answer 1

1

The "WordPress way" of making PHP values available to JavaScript is by enqueuing scripts and using wp_add_inline_script.

In your functions.php add an action hook for wp_enqueue_scripts. This hook is executed whenever scripts should be placed in the HTML.

In this hook you can register and enqueue scripts. That means we specify the files we need, and any dependency they have, for example jQuery, and couple an inline script with the PHP values to the JS file where we need the JSON in.

// Place me anywhere in functions.php.
add_action( 'wp_enqueue_scripts', function() {
  // Get all the products.
  $products = get_posts( array(
    'post_type'   => 'product',
    'numberposts' => -1,
  ) );
  
  // Turn the products into a JSON string.
  $products_json = json_encode( $products );
  
  // Register your script.
  // Check if the path to your JS file is correct.
  // get_theme_file_uri looks relative to the style.css file.
  wp_register_script( 'products', get_theme_file_uri( '/js/products.js' ), [], '1.0.0', true );

  // Add the inline script where the PHP data is turned into JavaScript.
  wp_add_inline_script( 'products', "window.__products__ = $products_json", 'before' ); 

  // Place both scripts in the HTML.
  wp_enqueue_script( 'products' );
} );

Now this specific function outputs an inline script <script>...</script> before a script with <script id="products-js" src="https://yoursite/path-to-script/main.js"></script>

The inline script creates a property on the window object which can be accessed from any file (as long as the file comes after the creation of the property).

// products.js file.
var products = window.__products__;
console.log(products);
Sign up to request clarification or add additional context in comments.

5 Comments

which part of this gets me the $json form the aforementioned index.php loop, or I dont need it anymore?
The aforementioned loop in the index.php file can be omitted. Though I would recommend that you would check if the value of $products is exactly what you're looking for. WP has a lot of helper functions and you will rarely need to write your own SQL queries, except if there is no existing way of getting what you need from the DB. But get_posts() will get an array of WP_Post objects, which contain every piece of information of each product. You can make the query of get_posts() more specific when needed.
it seems that the page outputs only white. Odd
The WSOD (White Screen Of Death) indicates that there is a fatal error in the PHP code. Make sure the PHP is inside of <?php and ?> in your functions.php file. If that's not it, comment everything inside of the function() {} block out and reactive everything piece by piece until the code breaks again. Then we'll know more. Oh, and go to your wp-config.php and enable debuggin by setting define( 'WP_DEBUG', true );. This line is probably already in that file, but with the value false. Change it to true.
My apologies. There was a space between the double underscore and products. Please try the example again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.