Search code examples
wordpresslang

How to query the custom fields by language in wordpress?


For each post, there is a custom field name "Function", the key/value pair is like this:

Key : Functions
Value : <!--en-->Nourishing Yin and invigorating the vital essence of kidneys.<!--:--><!--tw-->滋陰補腎。<!--:-->

The problem is if I simply use get_post_meta , it return string of both language, how can I get the value based on the language?

I am using qTranslate right now, Thanks.

Updated (the code):

$custom_fields = get_post_custom(get_the_ID());
$function = get_post_custom_values('Functions', get_the_ID());

Solution

  • You can simply fetch the strings considering comments as prefix and suffix -

    After you get the custom field value,

    e.g.

    $function = "<!--en-->Nourishing Yin and invigorating the vital essence of kidneys.<!--:--><!--tw-->滋陰補腎。<!--:-->";
    
    $arr = explode("<!--:-->", $function);
    
    $new_arr = array();
    
    foreach($arr as $a ){
    
     if(!empty($a)){
        $lang = str_replace( "-->", "", substr($a, 4, 5) );
        $str = substr($a, 9);
        $new_arr[$lang] = $str;
     }
    
    }
    

    Now $new_arr will have key/value pairs like array(language_code => sentence).

    If you do print_r($new_arr);

    It will give output as follows:

    Array ( [en] => Nourishing Yin and invigorating the vital essence of kidneys. [tw] => 滋陰補腎。 )
    

    Now you can identify the strings using their respective language codes.