Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save roelven/406636 to your computer and use it in GitHub Desktop.
Save roelven/406636 to your computer and use it in GitHub Desktop.
Retrieve a string in a specific language when using qTranslate
/*
How to print a string in both (or more) languages when using qTranslate on Wordpress
qTranslate provides Wordpress with multilanguage support and automates this in a pleasant way.
However you might want to print a specific string in a specific language, somewhere in your
theme or module.
Use this function to extract the content from the qTranslate quicktags, and retrieve the
title directly from the database using this query.
You can put the function in your functions.php.
Be careful with using SQL queries in your themefiles. This should never be a good idea!
This is just for demonstrating purposes since qTranslates' support fora isn't doing a better job.
qTranslate: http://www.qianqin.de/qtranslate/
Wordpress wpdb class: http://codex.wordpress.org/Function_Reference/wpdb_Class
Your Neighbours: http://yourneighbours.de/
*/
function ynbs_translatethis($content) {
$regexp = '/<\!--:(\w+?)-->([^<]+?)<\!--:-->/i';
if(preg_match_all($regexp, $content, $matches)) {
$output = array();
$count = count($matches[0]);
for($i = 0; $i < $count; $i++) {
$output[$matches[1][$i]] = $matches[2][$i];
}
return $output;
} else {
return 'no matches';
}
}
global $wpdb;
$posttable = $wpdb->prefix.'posts';
$raw_title = $wpdb->get_var($wpdb->prepare("SELECT post_title FROM $posttable WHERE id = $post_ID"));
$ynbs_post_title = ynbs_translatethis($raw_title);
print $ynbs_post_title['en'];
print $ynbs_post_title['de'];
@tap3ah
Copy link

tap3ah commented Oct 17, 2012

I don't think that '[^<]' is acceptable. $content can be, and usually is, HTML code.

@vp360
Copy link

vp360 commented Oct 26, 2012

for me is echoing "n"
how come?
i'm using this code to test it, and I've pasted the function in functions.php in my theme

    $cattt = "Testname";
$ynbs_cat_title = ynbs_translatethis($cattt);
if (qtrans_getLanguage() =="it") {
$cat_name = $ynbs_cat_title['it'];
echo $cat_name;
}
if (qtrans_getLanguage() =="en") {
$cat_name = $ynbs_cat_title['en'];
echo $cat_name;
}
if (qtrans_getLanguage() =="fr") {
$cat_name = $ynbs_cat_title['fr'];
echo $cat_name;
}
if (qtrans_getLanguage() =="es") {
$cat_name = $ynbs_cat_title['es'];
echo $cat_name;
}
if (qtrans_getLanguage() =="de") {
$cat_name = $ynbs_cat_title['de'];
echo $cat_name;
}

thanks

Copy link

ghost commented Nov 3, 2014

Awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment