get_terms returns empty array in integration test

by mcon   Last Updated November 14, 2017 18:08 PM

I'm leveraging WordPress' PHPUnit to run some integration tests, and I'm getting inconsistent results depending on whether WooCommerce is activated or not.

Without activating WooCommerce, I set up all the necessary taxonomy and term data, then create a product and tag it.

$level = $this->factory->post->create(
    array(
        'post_title' => 'Test Product',
        'post_type' => 'product',
        'post_status' => 'published'
    )
);
$tagged = wp_set_object_terms($level, 'Level 1', 'product_tag', true);

After tagging all my posts, if I do get_the_terms($level, 'product_tag') it returns expected:

[{" term_id":2,"name":"Level 1","slug":"level-1","term_group":0," term_taxonomy_id":2,"taxonomy":"product_tag","description":"","parent":0,"count":5,"filter":"raw"}]

In this set up, everything works fine, but later in my test I have to run

$args = array( 'post_type' => 'product', 'posts_per_page' => -1, 'product_tag' => $tag );
$products = get_posts( $args );

Which doesn't return any products—presumably because the product post type hasn't been registered.

If I activate WooCommerce in my test or register a product post type, I start getting weird results. wp_set_object_terms appears to be working because running get_the_terms( ... ) for an individual product will return

[{"term_id":15,"name":"Level 1","slug":"level-1","term_group":0,"term_taxonomy_id":15,"taxonomy":"product_tag","description":"","parent":0,"count":0,"filter":"raw"}]

Later on in my test, get_terms( 'product_tag' ) fires, but an empty array is returned. The only notable difference between the term meta in each set up is the count. 0 and 5 with and without WooCommerce activated, respectively.

Why are product tags not available when the product post type is registered?

I've also tried using wp_insert_post rather than the factory method, but it made no difference.



Related Questions


WP Unit tests error: WP_UnitTestCase not found

Updated May 21, 2015 00:03 AM

Proper unit testing in WordPress

Updated May 23, 2016 09:03 AM