Home Removing a value from an array. How can I get it to work
Reply: 1

Removing a value from an array. How can I get it to work

A3O
1#
A3O Published in 2018-01-13 07:21:45Z

I'm trying to create a custom navigation bar by using the category names of a custom post type. My approach is to create an array from the category names and create a navigation bar on the fly with the values from within the array. One of the category names is "uncategorized" and I want to get rid of that one.

The thing is that when I perform an array_search for 'uncategorized' nothing seems to be found and therefor nothing is unset. Can somebody shed some light on it? The array and the partial code is below.

The array ($categories) looks like this:

[3] => WP_Term Object
    (
        [term_id] => 2
        [name] => Logo
        [slug] => logo
        [term_group] => 0
        [term_taxonomy_id] => 2
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 10
        [filter] => raw
        [cat_ID] => 2
        [category_count] => 10
        [category_description] => 
        [cat_name] => Logo
        [category_nicename] => logo
        [category_parent] => 0
    )

[4] => WP_Term Object
    (
        [term_id] => 1
        [name] => Uncategorized
        [slug] => uncategorized
        [term_group] => 0
        [term_taxonomy_id] => 1
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 7
        [filter] => raw
        [cat_ID] => 1
        [category_count] => 7
        [category_description] => 
        [cat_name] => Uncategorized
        [category_nicename] => uncategorized
        [category_parent] => 0
    )

My code so far looks like this:

<?php if ( get_post_type( get_the_ID() ) == 'work' ) {
 $categories = get_categories( array() );?>

<!-- display the contents of the array before unset -->
<pre>
  <?php print_r($categories);?>
</pre>
<!-- End display -->

<?php $key = array_search('uncategorized', $categories);
  printf ($key);
  unset($categories [$key]);

  // display contents of the array after unset
  foreach ( $categories as $category ) {
  printf( $category->name );
  // end display
  }
}
?>
Franco De Leon
2#
Franco De Leon Reply to 2018-01-13 07:37:46Z

You can add an if in the foreach:

if($category->name != 'Uncategorized') {
    printf($category->name);
}

That's it.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328632 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO