i need to get only sub category ID. i already get sub category id but it coming with main category id too

bellow is code

<?php while ( have_posts() ) : the_post(); ?>

<option value=".<?php
     foreach((get_the_category()) as $category) {
     echo $category->cat_ID . ' '. $category->cat_name ;
     }
     ?>">
              <?php
     foreach((get_the_category()) as $category) {
     echo $category->cat_name . ' ';
     }
     ?>

</option>
<?php endwhile; 
?>

after code my rendered code is like bellow

<select id="filter-select">
          <option value="*" selected="selected">all</option>
                    <option value=".15 8 ">Magdalena Venta </option>
                    <option value=".15 8 ">Bo. de la Magdalena</option>
                    <option value=".16 8 ">Juan Venta</option>
                    <option value=".17 8 ">Club de G</option>
                    <option value=".21 8 ">Fraccionamiento Viñedos Venta</option>
</select>

after value all is sub category id like 15, 16, 17,21 but 8 is is main category ID. i don’t want this 8 coming.

so mainly i want to get like this <option value="child category ID ">Child Category Name </option>

i am trying still. if i get can get any solution it will post here

3 Answers
3

As you only want a select form field that has a categories children, then simply go with wp_list_categories()

wp_list_categories( array(
    'child_of' => 'your parent cat ID',
) );

Depending on your use case, you could as well use

  • get_the_category() and its get_the_categories filter

    apply_filters( 'get_the_categories', $categories );
    
  • get_the_terms() and its filter (the function is called internally by get_the_category():

    apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
    
  • get_categories(), pass a special key to the arguments input array (e.g. my-special-list) that you then check in a callback on the filter inside the function and alter the output there. The function calls get_terms() after the filters callbacks get called.

    apply_filters( 'get_categories_taxonomy', $taxonomy, $args );
    
  • get_term_children( $term_ID, 'category' )

Edit The main queried object can always be retrieved using get_queried_object(). And there’s a function to extract its ID: get_queried_object_id().

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *