Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught Error: Class 'WP_Query' not found in url - Wordpress

i created an ajax file that pass ID in the page. and that page has a query. and i got an error. I try to know what is my error and some site said i have to define my template and require the wp-load.php, but some site said that i have to do it on function.php. and i really don't know what to do. i'm new in wordpress woocommerce.

Uncaught Error: Class 'WP_Query' not found in xxxx/xxxx

Here is my Page (get-fabric.php)

   <?php  


    if(!empty($_POST['select_colour']))
    {
        $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 1000,
        'product_cat'    => 'fabric'


        );

        $query = new WP_Query($args);


            while ( $query->have_posts() ) : $query->the_post();
            global $product;
            $regular_price = $product->get_price_html();

            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $query->post->ID ), 'product' );
                echo '  <div class="col-md-3 fabric-active" data-fabcode="32860">
                <div class="fabric-cloth">
                    <div class="fabric-data">
                        <img src="'.$image[0].'" class="img-responsive cursor-on" />
                        <div class="fabric-code">
                            <p>'.$product->post->post_title.'</p>
                            <span>'.$regular_price.'</span>
                        </div>
                    </div>
                </div>
            </div>';
            endwhile;

    wp_reset_query();
    ?>
    <div class="col-md-3 fabric-active" data-fabcode="32860">
                <div class="fabric-cloth">
                    <div class="fabric-data">
                        <img src="'.$image[0].'" class="img-responsive cursor-on" />
                        <div class="fabric-code">
                            <p>'.$product->post->post_title.'</p>
                            <span>'.$regular_price.'</span>
                        </div>
                    </div>
                </div>
            </div>
  <?php
     }
  ?>
like image 789
user3678152 Avatar asked Jan 22 '18 03:01

user3678152


Video Answer


1 Answers

If you are calling this url directly, which is not how WordPress ajax is intended to work, you can still get this code to run by adding this php code

$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );

to the top of the file.

https://codex.wordpress.org/AJAX_in_Plugins I know this says Ajax in plugins but this is also what you would do if developing a custom theme to keep your code WordPress-y.

like image 160
JasonB Avatar answered Oct 11 '22 06:10

JasonB