skip to Main Content

I need to get term for current custom post dynamically on single page (for breadcrumbs for example)
I used get_the_terms( $post->ID, ‘curr_post_tax’ )
Or how to get curr_post_tax of current custom post
Or maybe you know others methods

Home>Catalog>Term>CurrProd

2

Answers


  1. The get_the_terms() function returns an array of terms of the specified taxonomy. If you want just the first term from that array then:

    $terms = get_the_terms( get_the_ID(), 'YOUR-TAXONOMY' );
                            
    if ( $terms && ! is_wp_error( $terms ) ) : 
      echo $terms[0];
    endif;
    
    Login or Signup to reply.
  2. Since you ask how to get the term for a Post without knowing the taxonomy in advance, we cannot use these functions because a $taxonomy or $taxonomies parameter is required:

    Finding a term for a Post without reference to the taxonomy means you could be finding any kind of term: tag, category, custom_taxonomy_1, custom_taxonomy_2, etc. If a Post has a tag term and a category term, how will your breadcrumb know which term to use without knowing the taxonomy?

    If you can guarantee that a Post has only one term, and that term is always a valid navigation breadcrumb, then searching without the taxonomy would be safe, and you could try the function below.

    Function: get_term_without_taxonomy

    /**
     * Find a term for a Post using the term with the
     * lowest term_id (this can be changed by updating
     * the SQL statement).
     *
     * @param int     $post_id The WP_Post database ID.
     *
     * @return object $term    An object with properties from WP_Term.
     */
    function get_term_without_taxonomy( int $post_id ): object|null {
        global $wpdb;
        $table_prefix = $wpdb->prefix;
    
        $sql = "";
        $sql .= "SELECT T.*, TT.taxonomy";
        $sql .= " FROM {$table_prefix}terms T";
        $sql .= " JOIN {$table_prefix}term_taxonomy TT ON ( TT.term_id = T.term_id )";
        $sql .= " JOIN {$table_prefix}term_relationships TR ON ( TR.term_taxonomy_id = TT.term_taxonomy_id )";
        $sql .= " JOIN {$table_prefix}posts P ON ( P.ID = TR.object_id )";
        $sql .= " WHERE P.ID = %d";
        $sql .= " ORDER BY T.term_id ASC";
        $sql .= " LIMIT 1";
        $sql .= ";";
    
        $query = $wpdb->prepare( $sql, $post_id );
    
        $term = $wpdb->get_row( $query, OBJECT );
    
        return $term;
    }
    
    /**
     * Pseudo-code example.
     */
    $post_id = 1;
    $term = get_term_without_taxonomy( $post_id );
    // To get the taxonomy: $term->taxonomy
    if ( is_object( $term ) ) {
        $breadcrumb = $level_1->name . ' > ' . $level_2->name . ' > ' . $term->name;
    } else {
        // Oops. This Post has no term!
        $breadcrumb = $level_1->name . ' > ' . $level_2->name;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search