get_term_children solo per i figli diretti (non i nipoti)

25 nov 2013, 07:39:11
Visualizzazioni: 20.9K
Voti: 8

Voglio visualizzare i termini figli di una tassonomia personalizzata. Attualmente, riesco a farlo usando get_term_children, ma questo mostra sia i figli che i nipoti, mentre vorrei evitarlo e far sì che vengano mostrati solo i figli diretti.

Questo è quello che ho al momento (ma mostra sia figli che nipoti):

<?php
$term_id = get_queried_object_id();
$taxonomy_name = 'mytaxname';

$termchildren = get_term_children( $term_id, $taxonomy_name );

foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo ' <div class="product-archive">';
        echo '<div class="post-title">
      <h3 class="product-name"><a href="' .get_term_link( $term, $taxonomy_name ). '">' .$term->name. '</a></h3>  
    </div>
  </div>';  }
?>

Questo è quello che sto cercando di far funzionare per mostrare solo i figli diretti:

<?php
$term_id = get_queried_object_id(); 
$taxonomy_name = 'mytaxname';

$args = array('parent' => $term_id,'parent' => $term_id );
$termchildren = get_terms( $taxonomy_name, $args);

foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo ' <div class="product-archive">';
        echo '<div class="post-title">
      <h3 class="product-name"><a href="' .get_term_link( $term, $taxonomy_name ). '">' .$term->name. '</a></h3>  
    </div>
  </div>';  }
?>

Questo mi restituisce un errore:

Catchable fatal error: Object of class WP_Error could not be converted to string in...

Cosa ho sbagliato?

Grazie!

0
Tutte le risposte alla domanda 1
1
13

Usa la funzione get_terms() invece:

$term_children = get_terms(
    'mytaxname',
    array(
        'parent' => get_queried_object_id(),
    )
);

if ( ! is_wp_error( $terms ) ) {
    foreach ( $term_children as $child ) {
        echo '
            <div class="product-archive">
                <div class="post-title">
                    <h3 class="product-name"><a href="' . get_term_link( $child ) . '">' . $child->name . '</a></h3>
                </div>
            </div>
        ';
    }
}

get_terms() può restituire un oggetto WP_Error, quindi è necessario verificare che non lo faccia. Restituisce un array di oggetti term, quindi non è più necessario recuperare gli oggetti con get_term_by(). Poiché $child è un oggetto term, get_term_link() non necessita del secondo parametro. get_terms() ha più opzioni per il secondo parametro. Dovresti dare un'occhiata.

25 nov 2013 18:55:22
Commenti

Dalla versione 4.5.0 la tassonomia dovrebbe essere inclusa nell'array args $term_children = get_terms( array( 'taxonomy' => 'mytaxname', 'parent' => get_queried_object_id(), ) );

Juniper Jones Juniper Jones
28 mag 2020 21:23:16