Get parent term name and URL in MBViews

Support MB Views Get parent term name and URL in MBViewsResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #43034
    RoderickRoderick
    Participant

    Hi,

    I am using mbviews for my child-category/term archives. Is there a way to get the parent-category name and URL?

    My use case: I want to display a banner on a child-category archive that points to the parent-category.
    For example.
    - New York
    -- Activities

    On the 'Activities archive' I wish to show a banner with the name 'All New York articles' that links to the New York parent.

    Unfortunately I can't seem to find a default field for this in the MB Views sidebar.
    I hope you can help me with this.

    Thank you in advance 🙂

    Roderick

    #43051
    PeterPeter
    Moderator

    Hello,

    There isn't a default field for the parent term of the current term. You can use some WordPress functions to get the parent term name and permalink. For example:

    {% set current_term = mb.get_term_by( 'id', term.id, 'category' ) %}
    {% set parent_term = mb.get_term_by( 'id', current_term.parent, 'category' ) %}
    
    Parent term name: {{ parent_term.name }}
    <br>
    Parent term permalink: {{ mb.get_term_link( parent_term, 'category' ) }}

    Please read more in the documentation
    https://docs.metabox.io/extensions/mb-views/#running-php-functions
    https://developer.wordpress.org/reference/functions/get_term_by/
    https://developer.wordpress.org/reference/functions/get_term_link/

    #43074
    RoderickRoderick
    Participant

    Thank you once again Peter, it works perfectly!

    For future reference, here is my finished MB views code:

    {% set current_term = mb.get_term_by( 'id', term.id, 'category' ) %}
    {# Check to see if the current term has a parent #}
    {% if current_term.parent %}
    {% set parent_term = mb.get_term_by( 'id', current_term.parent, 'category' ) %}
    <div>
    <a href="{{ mb.get_term_link( parent_term, 'category' ) }}">
    All posts of <span>{{ parent_term.name }}</span>
    </a>
    </div>
    {% endif %}
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.