Get posts by category and language, using PolyLang
Asked Answered
R

1

5

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?

Remove answered 21/6, 2017 at 9:46 Comment(0)
V
8

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 ); ?>
Venesection answered 16/8, 2017 at 9:39 Comment(2)
Couldn't be better explained! Thanks a lot, Joris!Remove
Great solution, it helped me a lot for a custom taxonomy 'tax_query' => array(array('taxonomy' => 'taxonomy-slug', 'field' => 'term_id', 'terms' => pll_get_term(34)))Smithery

© 2022 - 2024 — McMap. All rights reserved.