6

No matter whether I use it from my page in French version or in English version, wp_query() returns my custom post types in all languages, not just in the current one. Get_posts() does the same thing too.

When I visit my page in French, I want them to return CPTs in the current language only. How to achieve that?

drake035
  • 3,955
  • 41
  • 119
  • 229

2 Answers2

15

When using get_posts(), set suppress_filters to false:

$myPosts = get_posts(array(
    'suppress_filters' => false
));

http://codex.wordpress.org/Function_Reference/get_posts#Parameters

P-S
  • 3,876
  • 1
  • 29
  • 26
3

That's the best way I found to fetch posts on a specific language using WPML...

In my case I need to find a post by it's title on a specific language and return the ID of the post:

$lang='en';
$title='The title you are searching!';

    function getWpIdByTitle($title, $lang){
        global $sitepress;
        // WPML Super power language switcher...
        $sitepress->switch_lang( $lang );
        $args = array(
          'title'        => $title,
          'post_type'   => 'your-post-type', // Default: post
          'post_status' => 'publish',
          'suppress_filters' => false,
          'numberposts' => 1
        );
        $wp_query = new WP_Query( $args );
        return $wp_query->post->ID;
    }

You may use the $wp_query->post as the result of the fetch and do the echo's of title, content, etc.

This way you don't need to use the

do_action( 'wpml_set_element_language_details', $set_language_args );

to connect your language posts, neither the

icl_object_id(1,'post',false,ICL_LANGUAGE_CODE);

to get the ID of a post on a specific languange.

gtamborero
  • 2,898
  • 27
  • 28
  • 1
    Top! Also, I would reset $sitepress->switch_lang() to the $current_language after use. I was using this inside a shortcode, ran the query, but then couldn't see any product because I forced the language change. Restoring the previous language made it work – businessbloomer Mar 17 '23 at 16:34