Get posts by category and language, using PolyLang

Italo Borges picture Italo Borges · Jun 21, 2017 · Viewed 12.7k times · Source

I'm creating a plugin and I already could get the posts by category and by the current language using get_posts() function from WordPress and passing the attribute lang with the pll_current_language() from PolyLang.

$args = array(
    'posts_per_page'   => 6,
    'orderby'          => 'date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'lang'             => pll_current_language()
);
return get_posts($args);

Now, I'm wondering how to get the posts by categories related to the language? For example, I have the News category for English and Noticias for Spanish. How can I set this automatically?

Something like this:

$args = array(
    ......
    'category' => **current_category_for_this_language**
    ......
);
return get_posts($args);

Any ideas?

Answer

Joris Kroos picture Joris Kroos · Aug 16, 2017

Use pll_get_term and filter by category. In this case '34' is my term ID (gotten by hovering the edit link of the term).

By the way as far as I know get_posts gets only posts in the current page language by default and it gets posts by default sorted by date DESC, so you could omit those from your query I think.

$args = array(
  'posts_per_page'   => 6,
  'category'         => pll_get_term(34)
);
return get_posts($args);

Sources

https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/

pll_get_term

Returns the category (or post tag) translation

Usage:

pll_get_term($term_id, $slug);

‘$term_id’ => (required) id of the term you want the translation

‘$slug’ => (optional) 2-letters code of the language, defaults to current language

https://codex.wordpress.org/Template_Tags/get_posts

Default Usage

<?php $args = array(
  'posts_per_page'   => 5,
  'offset'           => 0,
  'category'         => '',
  'category_name'    => '',
  'orderby'          => 'date',
  'order'            => 'DESC',
  'include'          => '',
  'exclude'          => '',
  'meta_key'         => '',
  'meta_value'       => '',
  'post_type'        => 'post',
  'post_mime_type'   => '',
  'post_parent'      => '',
  'author'       => '',
  'author_name'      => '',
  'post_status'      => 'publish',
  'suppress_filters' => true 
);
$posts_array = get_posts( $args ); ?>