MB Views get term name

Support MB Views MB Views get term name

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #33349
    BellulBellul
    Participant

    I use this code to get post titles and permalinks for at custom post type:

    {% for report in reports %}
        <p><a href="{{ mb.get_permalink( report.ID ) }}">{{ report.post_title }}</a></p>
    {% endfor %}

    And it works fine.

    But I also want to get the post's "published year" (a custom term field). If I click on Insert Field in Edit View, choose the the field "kb_year", and in the popup "Taxonomy settings" choose "Term Name" as "Output", I get this code:

    {{ post.kb_year.name }}

    How do I "convert" that code in my context? I have tried different ways (e.g. {{ mb.rwmb_meta( 'kb_year', {'object_type': 'term'}, report.ID ) }} - report.ID should maybe be the term id, but how do I get that?), but nothing works.

    #33370
    Long NguyenLong Nguyen
    Moderator

    Hi Bellul,

    You need to get the post terms based on the post ID first, then use the for loop to iterate each term to get the term ID. For example:

    {% for report in reports %}
        <p><a href="{{ mb.get_permalink( report.ID ) }}">{{ report.post_title }}</a></p>
        {% set my_post_terms = mb.wp_get_post_terms( report.ID, 'taxonomy_slug' ) %}
        {% for my_term in my_post_terms %}
            {{ mb.rwmb_meta( 'kb_year', {'object_type': 'term'}, my_term.term_id ) }}
        {% endfor %}
    {% endfor %}

    Refer to the documentation https://developer.wordpress.org/reference/functions/wp_get_post_terms/

    #33397
    BellulBellul
    Participant

    Thanks, this seems to be the way. But it seems as if the array my_post_terms is empty (since the for loop does not outputs anything - I tested just to output a manual textstring). My taxonomy slug is "kb-pubyear". Is it a problem that the slug use a dash and not an underscore?

    #33429
    Long NguyenLong Nguyen
    Moderator

    Hi,

    There is no problem with the dash or underscore character. Please correct the field ID, taxonomy slug (not the term slug) and check the output value again.

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.