• Resolved citrondesignoffice

    (@citrondesignoffice)


    I use polylang plugin.
    I created taxonomy(ex.my_taxonommy) and created a term (ex.my_term) for ‘my_taxonomy’.
    and then I added a term(ex.my_term_en) as a translation for ‘my_term’.

    Now I want to count posts which terms are ‘my_term_en’.

    I used ‘get_term_by’ like:

    $count = get_term_by(‘slug’,’my_term_en’,’my_taxonomy’);
    $cnt = $count->count;

    But ‘get_term_by’ returns bool(false).

    I treid,
    $count = get_term_by(‘slug’,’my_term’,’my_taxonomy’);
    and this could be OK.
    I know ‘my_term’ is default language.

    How can I do this?

    Thanks for your help.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Chouby

    (@chouby)

    Hi,

    get_term_by() is filtered by the current language. So if you attempt to get a term by a slug which doesn’t exist in the current language, then it’s expect that you get an empty result.

    Use get_terms() instead. You can explicitely set the lang parameter to get the terms in a different language, or to an empty value to get the terms in all language.

    See https://polylang.pro/doc/developpers-how-to/#query The example uses get_posts() but it works the same for get_terms()

    veerap

    (@veerap)

    Get term by id instead of slug so you can check for translations.

    Example:

    // Check if Polylang is active and get term ID (123) from "my_term".
    $term_id = ( function_exists( 'pll_get_term' ) ) ? pll_get_term( 123 ) : 123;
    // Get term by ID.
    $term = get_term_by( 'id', $term_id, 'my_taxonomy' );
    // Output the result.
    echo '<span>' . $term->name . ' / '. $term->count . '</span>';

    https://polylang.pro/doc/function-reference/#pll_get_term

    Thread Starter citrondesignoffice

    (@citrondesignoffice)

    Hi.
    @chouby I understood.Thanks for your help.
    @veerap I’ll tried this too.Thanks for your help.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[polylang]count posts using ‘get_term_by’’ is closed to new replies.