Get messages by category and language using PolyLang
I am creating a plugin and I could already get posts by category and current language using get_posts () function from WordPress and passing the lang attribute using 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 am wondering how to get posts by language related categories? For example, I have a news category for English and Noticias for Spanish. How can I set this automatically?
Something like that:
$args = array(
......
'category' => **current_category_for_this_language**
......
);
return get_posts($args);
Any ideas?
source to share
Use pll_get_term and filter by category. In this case, "34" is my term id (obtained from the hovering term edit link).
By the way, as far as I know, get_posts only has posts in the current language by default, and by default they are sorted by DESC date, so you can omit those from your query, I guess.
$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 translation of a category (or post)
Using:
pll_get_term($term_id, $slug);
'$ term_id => (required) id of the term you want to translate
'$ slug => (optional) 2-letter language code, defaults to the current language
https://codex.wordpress.org/Template_Tags/get_posts
Default use
<?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 ); ?>
source to share