0

I want to create a selector control in the Wordpress customizer with all the existing categories and for that I need an array with all the categories and their names.

I need to get an array like this:

[
        'category_one' => esc_html__( 'Category name 1', 'kirki' ),
        'category_two' => esc_html__( 'Category name 2', 'kirki' ),
        'category_three' => esc_html__( 'Category name 3', 'kirki' ),
        'category_four' => esc_html__( 'Category name 4', 'kirki' ),
],

(I'm using the Kirki framework, but that's AFAIK not very relevant to this question, because it is only about getting the array).

I figured out I could do it with something like this:

    $categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => 0
) );
    

but that gives me a way too complex array with too much information.

If it is possible, it would be great if the same could also be done with tags and then combined into one array. The combining can be done with a PHP-operator, it's really about getting an array with the category and the name.

Thanks a lot in advance!

1 Answer 1

1

This part of code from the question will fetch only parent category because 'parent' => 0, drop this from array if you need all the categories

$categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => 0
) );

// You can iterate over the list of objects returned by `get_categories` 
// to achieve list of categories in required format.

$category_list = array();
foreach( $categories as $category ) {
    $category_list[$category->slug] = esc_html__( $category->name, 'kirki' );
}
1
  • Hi @ViralP thanks a lot for the answer and for showing me the technique on how to reformat such data. Cheers, Ralph
    – ralphjsmit
    Commented Jun 20, 2020 at 18:03

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.