plugins - How to pass all received IDs through the function for in_category

admin2025-04-22  0

There is a function that receives from the main category everything in its sub categories:

function get_cats(){
  $id       = 1;
  $tax  = 'category';
  $children = get_term_children( $id, $tax );

  foreach ( $children as $child ) {
    $term = get_term_by( 'id', $child, $tax );
    echo ''. $term->term_id .',';
  }
}

I need to pass all the received ID in the condition:

if ( in_category( array( get_cats() ) ) ) {
  //
}

Values are transmitted, but the entries themselves in these categories are not displayed, but only the id from the function How to transfer them in in_category?

There is a function that receives from the main category everything in its sub categories:

function get_cats(){
  $id       = 1;
  $tax  = 'category';
  $children = get_term_children( $id, $tax );

  foreach ( $children as $child ) {
    $term = get_term_by( 'id', $child, $tax );
    echo ''. $term->term_id .',';
  }
}

I need to pass all the received ID in the condition:

if ( in_category( array( get_cats() ) ) ) {
  //
}

Values are transmitted, but the entries themselves in these categories are not displayed, but only the id from the function How to transfer them in in_category?

Share Improve this question asked Jul 30, 2019 at 12:31 user3622103user3622103 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You can't pass arrays by passing a string with commas into array(), that's not how arrays work in PHP. Your code is the equivalent of:

if ( in_category( array( '1,2,3,4' ) ) ) {
}

Which is checking for a single category with the ID '1,2,3,4', which can't exist.

For what you want to do, your function needs to return an array of IDs, which will be passed directly into in_category(), without array():

function get_cats(){
  $id       = 1;
  $tax      = 'category';
  $children = get_term_children( $id, $tax );
  $cats     = array(); // Prepare an array to return.

  foreach ( $children as $child ) {
    $term   = get_term_by( 'id', $child, $tax );
    $cats[] = $term->term_id; // Add ID to the array:
  }

  return $cats; // Return the array.
}

Then:

if ( in_category( get_cats() ) ) {
  //
}

However, it needs to be pointed out that your get_cats() function is extremely redundant. You're using get_term_children() to get the IDs of the children, but then for some reason you're looping through those IDs to get the full term, just so you can get the ID. This doesn't make sense, because you already had the IDs.

So really, you don't need the get_cats() function at all. Just use get_term_children():

$term_ids = get_term_children( 1, 'category' );

if ( in_category( $term_ids ) ) {

}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745284129a294284.html

最新回复(0)