0

I wrote the following lines of code. It shows a dropdown menu with all available Wordpress categorys in the Wordpress customizer and can output the category slug. But instead of the slug I want to output the category id. Does anyone have an idea how to realize that?

$categories = get_categories();

$cats = array();
$i = 0;
foreach($categories as $category){
    if($i==0){
        $default = $category->slug;
        $i++;
    }
    $cats[$category->slug] = $category->name;
}

$wp_customize->add_setting('wptimes_homepage_featured_category', array(
    'default'        => $default
));

$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'wptimes_homepage_featured_category', array(
    'label' => 'Hervorgehobene Kategorie',
    'description' => 'Wähle hier die Kategorie aus, die du auf der Startseite hervorheben möchtest.',
    'section' => 'wptimes_homepage',
    'settings' => 'wptimes_homepage_featured_category',
    'type'    => 'select',
    'choices' => $cats
)));
0

In your foreach loop just do a quick print_r($category) to see all available options.

Than you will see that you can use $category->term_id to get the ID of the term/category, instead of $category->slug.

So for example, by using your code from above:

$categories = get_categories();

$cats = array();
$i = 0;

foreach( $categories as $category ) {

    // uncomment to see all $category data
    #print_r($category);

    if( $i == 0 ){

        $default = $category->term_id;
        $i++;

    }
    $cats[$category->term_id] = $category->name;
} 

print_r($cats);
// Prints for example: Array ( [12] => Child-Cat [2] => Parent-Cat [1] => Uncategorized ) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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