1

I need an array of custom taxonomy slugs. In the front-end, I get it using get_terms():

$tax_slugs = get_terms( 'course', array( 'fields' => 'slugs', 'parent' => 0, 'hide_empty' => 0 ));
print_r($tax_slugs);

result: Array ( [0] => breakfast [1] => lunch [2] => dinner [3] => dessert ) 

In the admin, the "Invalid Taxonomy" error will be raised by the function get_terms() because I've registered my taxonomy on the init action hook.

I need a function with SQL query and prepare method, to get an array of custom taxonomy slugs, like the one obtained with get_terms()

4
  • Is there a reason you need them before the init hook? Sep 18, 2017 at 8:11
  • I need it to create a theme option to sort the posts by taxonomy.
    – Giorgia
    Sep 18, 2017 at 11:28
  • That doesn't explain why you can't do it after the init hook. Where you creating theme options? Sep 18, 2017 at 11:37
  • I'm using Redux Framework to create theme options and I always get "Invalid Taxonomy" error in the backend, except with SQL query
    – Giorgia
    Sep 18, 2017 at 11:58

1 Answer 1

1
global $wpdb;

$slugs = $wpdb->get_col(
    "SELECT
        slug
    FROM
        $wpdb->terms
    LEFT JOIN
        $wpdb->term_taxonomy ON
            $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
    WHERE
        $wpdb->term_taxonomy.taxonomy = 'course'"
);

That will return an array of strings representing the taxonomy term slugs for terms in the course taxonomy.

2
  • Thank you Jacob! Is it possible to select only parent terms and exclude empty ones?
    – Giorgia
    Sep 18, 2017 at 11:29
  • Yeah it's possible, you just need to modify the query to look at those columns. Term parents and counts are in the term_taxonomy table, so you'd add AND $wpdb->term_taxonomy.parent = 0 AND $wpdb->term_taxonomy.count > 0 to the WHERE clause. Sep 18, 2017 at 11:38

Your Answer

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

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