Question

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!

Was it helpful?

Solution

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' );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top