Skip to content

Instantly share code, notes, and snippets.

@varmais
Last active April 5, 2018 14:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save varmais/98e6f4c8872e7d00f0b6a89449dfc443 to your computer and use it in GitHub Desktop.
Save varmais/98e6f4c8872e7d00f0b6a89449dfc443 to your computer and use it in GitHub Desktop.
Fetch all latest Wordpress posts when using Polylang plugin
<?php
function get_default_language_posts($query)
{
if ($query->is_main_query() && is_home() && function_exists('pll_languages_list') && !is_admin()) {
$languages = pll_languages_list(array('hide_empty' => 1));
$terms = get_terms('post_translations');
$lang_default = pll_default_language();
$lang_current = pll_current_language();
$post_ids = array();
foreach ($terms as $translation) {
$transPost = unserialize($translation->description);
if ($transPost[$lang_current] != 0) { //has no translation in $lang_current
$post_ids[] = $transPost[$lang_default];
}
}
if ($lang_default != $lang_current) { //without this check, default language returns zero posts
$query->set('lang', join(',', $languages));
$query->set('post__not_in', $post_ids);
}
}
return $query;
}
add_filter('pre_get_posts', 'get_default_language_posts');
function get_latest_language_posts($atts)
{
global $polylang;
$output = '';
$attributes = shortcode_atts(array(
'number_of_posts' => 3
), $atts);
foreach ($polylang->get_languages_list() as $term) {
$langs[] = $term->slug;
}
$posts = get_posts(array(
'post_type' => 'post',
'lang' => implode(',', $langs),
'showposts' => $attributes['number_of_posts']
));
foreach ($posts as $post) : setup_postdata($post);
$permalink = get_permalink($post);
$output .= '<ul class="vm_latest_articles">';
$output .= '<li>';
$output .= "<a href='$permalink'>$post->post_title</a>";
$output .= '</li>';
$output .= '</ul>';
endforeach;
wp_reset_postdata();
return $output;
}
add_shortcode('latest_posts', 'get_latest_language_posts');
add_filter('widget_text', 'shortcode_unautop');
add_filter('widget_text', 'do_shortcode'); // you can use this on widget as a shortcode
[latest_posts number_of_posts=4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment