7

How can I make a call to WP_Query on plugin initialization and save posts data to $data?

I am getting Fatal error: Class 'ms\WP_Query' not found no matter on which hook I call the method. Even if I call it like this add_action('shutdown', array($this, 'get_data')); it doesn't work (shutdown hook is supposedly last to run) or if I call with a shortcode add_shortcode( 'get_data', array($get_data, 'get_data') );

<?php
/*
Plugin Name: Test
Description: Test
Version: 0.1
*/

namespace ms;

if (!defined('ABSPATH')) exit;

class get_data {

    private $data = array();    

    public function __construct(){
        // add_action('init', array($this, 'get_data'));
    }

    public function get_data() {

        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 10
            );

        $query = new WP_Query($args);

        if ( $query->have_posts() ) :
            while ( $query->have_posts() ) : $query->the_post();

                $this->data[] = array(
                    'title' => get_the_title()
                );

        endwhile;
        wp_reset_postdata();
        endif;

        var_dump($this->data);

    }

$get_data = new get_data();
add_shortcode( 'get_data', array($get_data, 'get_data') );

1 Answer 1

39

Because you're using a namespace in this class, you need to add a \ in front of the WP_Query call to tell PHP that it's in the global namespace and not the namespace of this class.

Try this: $query = new \WP_Query($args);

Not the answer you're looking for? Browse other questions tagged or ask your own question.