Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Joe Bruno
Joe Bruno
35,909 Points

WordPress: WP QUERY, Filters, And Calling A Static Method

Hello,

The Goal: Using a Custom WP Metaboxes plugin (https://github.com/webdevstudios/Custom-Metaboxes-and-Fields-for-WordPress), I am trying to add metaboxes to a custom post type, and I want one of my fields to dynamically create a drop-down list of all the "Stores" (another custom post type) that exists. I have created a function that gets all of the ideas of the Stores, and I can use a simply foreach loop to accomplish everything else needed.

The Problem: The line "add_filter('cmb_meta_boxes', 'cmb_sample_metaboxes');" is preventing me from successfully calling "$store = StripeTacular\Store::getStoreIDs();" I get an error: Fatal error: Call to undefined function is_user_logged_in() in /Applications/MAMP/htdocs/wp/wp-includes/query.php on line 3004. After much debugging, the problem seems to be that the WP Query class or something related to its methods is not available for whatever reason. The function works perfectly everywhere else I am using it, but it throws the error when coupled with the filter. I have tried calling the getStoresIDs method outside of the cmb_sample_metaboxes function and passing it into the function, but that also results in the same error, because, again, I think the code has already fired, but I don't know for sure.

Any help would be appreciated!

add_action('init', 'cmb_initialize_cmb_meta_boxes', 9999);

//This Filter is the issue
add_filter('cmb_meta_boxes', 'cmb_sample_metaboxes');

function cmb_initialize_cmb_meta_boxes()
{
    if (!class_exists('cmb_Meta_Box')) {
        require_once 'vendor/init.php';
    }
}

function cmb_sample_metaboxes(array $meta_boxes)
{
    $prefix = '_';

     //THIS STATIC METHOD THROWS THE ERROR
    $store = StripeTacular\Store::getStoreIDs(); // returns an array of ids

    $meta_boxes['metaboxes_books'] = array(
        'id'         => 'metaboxes_books',
        'title'      => __('Info', 'cmb'),
        'pages'      => array( 'books'), // Post type
        'context'    => 'normal',
        'priority'   => 'default',
        'show_names' => true, // Show field names on the left
        'fields'     => array(

            array(
                'name' => __('Price ($)', 'cmb'),
                'desc' => __('Enter the price of book. Do NOT use the $ symbol.', 'cmb'),
                'id'   => $prefix . 'the_price',
                'type' => 'text',
                'before'=> '',
            ),

getStoreIDs method:

 public static function getStoreIDs()
    {
        //loop through Organization post type; grab all IDs; load IDs into array;
        $loop = new \WP_Query(array( 'post_type' => 'Organizations', 'posts_per_page' => -1 ));
        $array = [];

        if ($loop->have_posts()) {

            while ($loop->have_posts()) {

                $loop->the_post();
                $id = $loop->post->ID;

                if ($id && !in_array($id, $array)) {

                    $array[] = $id;

                }
            } // end while
        } // end if

        return $array;
    }

4 Answers

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

Hey Joe, not sure from first glance what may be causing this. I'd try your question up on WordPress Stack Exchange

Joe Bruno
Joe Bruno
35,909 Points

Hey Zac, when are filters applied and fired in general as compared to the init hook on a add_action call? I ask because I think this is my issue. I think the Store class I created is being called too early within the filter. I think I need to delay somehow the filter? Any idea how to do that? I saw the add_action call has an option argument for priority, but I didn't see anything like this for filters in the WordPress Codex. Btw, I would love to see a detailed WP course from you at some point specifically on filters and actions hooks, and best practices on how and where to apply them within your own custom plugin creation. Thanks,

Zac Gordon
STAFF
Zac Gordon
Treehouse Guest Teacher

It's tricky to know when hooks are being called and applied, but you can look through the source code for

apply_filters( 'filter_name

You definitely don't want to try to delay the hook because it may break other things, but it is possible you are tying into the wrong hook. You may need to look for one that runs later.

I shot a course on WordPress Hooks last week ;) It should be up on the roadmap shortly :)

Joe Bruno
Joe Bruno
35,909 Points

Zac,

I was able to narrow the problem down directly to the creation of the new WP_Query object. It seems to be a runtime issue where the call is made before WP_Query is stable, and thus a fatal error is triggered.

$loop = new \WP_Query(array( 'post_type' => 'Organizations', 'posts_per_page' => -1 ));

resulted in a fatal error, but

 $args = array(
  'posts_per_page'   => 5,
  'offset'           => 0,
  'category'         => '',
  'category_name'    => '',
  'orderby'          => 'post_date',
  'order'            => 'DESC',
  'include'          => '',
  'exclude'          => '',
  'meta_key'         => '',
  'meta_value'       => '',
  'post_type'        => 'organizations',
  'post_mime_type'   => '',
  'post_parent'      => '',
  'post_status'      => 'publish',
  'suppress_filters' => true );
$posts_array = get_posts( $args );

ran successfully and all seems to be working correctly.

Any idea why get_posts works and WP_Query does not?

Thanks