0

I am trying to pass an array of category IDs to get_category_by_ID() in order to get an array of category names back. Since I'm still trying to get this to work I'm just using var_dump() on the output. I'm using the values 1, 5, 3 since 5 and 3 are categories I have and 1 is uncategorized, which I need this to work for.

I started with this:

    $CatID = array(1, 5, 3,);
foreach ($CatID as $ID) { 
    $names = get_the_category_by_ID($ID);
}
var_dump($names);

I returned the correct category name for category 3, but nothing else. So then I tried it like this:

$CatID = array(1, 5, 3,);
$x=0;
foreach ($CatID as $ID) { 
    if ($x==3) break;
    $names[$x] = get_the_category_by_ID($ID[$x]);
    $x++;
}
var_dump($names);

This time I got this array of errors:

array
0 => 
object(WP_Error)[262]
  public 'errors' => 
    array
      'invalid_term' => 
        array
          ...
  public 'error_data' => 
    array
      empty
 1 => 
 object(WP_Error)[261]
  public 'errors' => 
    array
      'invalid_term' => 
        array
          ...
  public 'error_data' => 
    array
      empty
2 => 
object(WP_Error)[215]
  public 'errors' => 
    array
      'invalid_term' => 
        array
          ...
  public 'error_data' => 
    array
      empty

1 Answer 1

1

Modify your first code chunk thusly:

$names = array();
$CatID = array( 1, 5, 3,);
foreach ( $CatID as $ID ) { 
    $names[] = get_the_category_by_ID( $ID );
    // uncomment the next line to get the name tied to the ID
    // $names[$ID] = get_the_category_by_ID( $ID );
}
var_dump( $names );

See PHP's array() reference for more info on using arrays.

Why your code isn't working

In your first example, you're looping through your $CatID array, assigning the return from get_the_category_by_ID() to $names. Each time through the loop, you're overwriting the $names variable, which is why only 3 -- the last one in your list -- is sticking.

In your second example, you're swinging too far the other way -- you're trying to get the value of $ID[$x], but $ID isn't an array, so you're handing an invalid value (probably null) to get_the_category_by_ID(). That's why it's returning a passel of WP_Error objects.

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.