-
-
Save ouun/c9a13397bb3a18c9e02e3345695eaed4 to your computer and use it in GitHub Desktop.
Fetch all latest Wordpress posts when using Polylang plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[latest_posts number_of_posts=4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment