How to find if first character is an underscore?

2512 views php
7

I tried this

foreach ($categories as $category) {
  if( $category[0] === '_'  ) {
    $option .= '<option>'.$category->name.'</option>';
  }
}

But gives me

Fatal error: Cannot use object of type WP_Term as array

I tried to use implode()

foreach ($categories as $category) {
  $string = implode($category);
  if( $category[0] === '_'  ) {
    $option .= '<option>'.$category->name.'</option>';
  }
}

But gives me

Warning: implode(): Argument must be an array

Fatal error: Cannot use object of type WP_Term as array

UPDATE

var_dump($categories);


array(1) { 
    [5]=> object(WP_Term)#999 (16) {
        ["term_id"]=> int(1) 
        ["name"]=> string(13) "Uncategorized" 
        ["slug"]=> string(13) 
        "uncategorized" 
        ["term_group"]=> int(0) 
        ["term_taxonomy_id"]=> int(1) 
        ["taxonomy"]=> string(8) "category" 
        ["description"]=> string(0) "" 
        ["parent"]=> int(0) 
        ["count"]=> int(9) 
        ["filter"]=> string(3) "raw" 
        ["cat_ID"]=> int(1) 
        ["category_count"]=> int(9) 
        ["category_description"]=> string(0) "" 
        ["cat_name"]=> string(13) "Uncategorized" 
        ["category_nicename"]=> string(13) "uncategorized" 
        ["category_parent"]=> int(0) 
    } 
}

answered question

Show your WP query.

Seems to me you're not dealing with a string. If I had to guess, I'd say it's a WP_Term, whatever that is. Try converting it to a string if you want to do a string comparison on it.

@miken32 is it not what i've tried with implode?

implode() is for arrays. As the error message says.

ehmm how would I convert it into a string then? @miken32

I'd suggest looking at the documentation for whatever kind of object you're dealing with. Many objects have a method to convert to a string, if it's reasonable to do so – depends on the object.

Also, while it's possible to use array syntax for extracting characters from strings, it's not a good idea. It confuses the code and makes it unclear what type of variable you're dealing with. Use substr.

@rob.m do var_dump($categories); and add the output in your question. You will get correct answer then only

@AlivetoDie updated the question

First character of what is an _? There are multiple strings in a category object...

had to tell wordpress to show categories even if empty, that's why i could only see one cat on the var_dump() so $args = array('hide_empty' => 0); $categories = get_categories($args); then the accepted answer for the underscore

1 Answer

6

Try this

foreach ($categories as $category) {
  if($category->name[0] == '_'){
    $option .= '<option>'.$category->name.'</option>';
  }
}

posted this

Have an answer?

JD

Please login first before posting an answer.