Wordpress : qTranslate X language switcher with language code - wordpress

I'm trying to make a basic language switcher with qTranslate X, something like :
FR | EN
There's a function to achieve that : qtranxf_generateLanguageSelectCode('text'); but it can only accept 'text', 'image' or 'both', so it doesn't fit to my needs : 'text' is the full name of the language.
How can I just show the language code ? Any idea to make a filter to do that ?

Try to add following script below translate code.
echo qtranxf_generateLanguageSelectCode('text');
<script>jQuery(document).ready(function(){ jQuery('.lang-en a span').html('EN'); jQuery('.lang-fr a span').html('FR'); })</script>
Serverside Solution:
Please find below Code which modify language name to language code without change in plugin code and you can do it by word press filter.
Paste below code into function.php file.
add_filter('template_include','start_buffer_EN',1);
function start_buffer_EN($template) {
ob_start('end_buffer_EN');
return $template;
}
function end_buffer_EN($buffer) {
return str_replace('<span>English</span>','<span>EN</span>',$buffer);
}
add_filter('template_include','start_buffer_FR',1);
function start_buffer_FR($template) {
ob_start('end_buffer_FR');
return $template;
}
function end_buffer_FR($buffer) {
return str_replace('<span>Français</span>','<span>FR</span>',$buffer);
}
You can change language name from wp-admin by edit language name directly..

Inspecting the plugin I found that generateLanguageSelectCode have more types than documented. So to use language codes you can simply just use the type 'short', like this:
qtranxf_generateLanguageSelectCode('short');
This might be a feature added since last answer.
Here is a overview of all the switcher types:
'text', 'image', 'both', 'short', 'css_only', 'custom', and 'dropdown'. I havn't looked into how the different types works, but you'll find them in qtranslate_widget.php in the plugin folder.

You could use widget for that
<?php the_widget('qTranslateXWidget', array('type' => 'custom', 'format' => '%c') );?>
(%c - Language 2-Letter Code)
It should be noted that if you would like to use dropdown type and 2-Letter Code - this won't work because format argument works only with 'custom' type. In this case I would go with Yehuda Tiram answer (especially if you have many languages and you don't know which languages your client will want to use).
More documentation here

A friend helped me with that and it's based on Ash Patel answer but in a cleaner way (IMHO) :
function my_qtranxf_generateLanguageSelectCode($style='', $id='') {
ob_start();
qtranxf_generateLanguageSelectCode($style, $id);
$o = ob_get_contents();
ob_end_clean();
return str_replace(array('English', 'Français'),array('EN', 'FR'), $o);
}

Why don't you just change the language name as per your needs?
It's possible in the language edit and does not affect anything.

I've done it using the following query and it is working fine for me.
<?php if (qtranxf_getLanguage() == 'ar') { ?>
<script>
jQuery(document).ready(function () {
var current_URL = jQuery(location).attr('href');
url = current_URL.replace('/ar/', '/en/')
jQuery('.languages-selection ul li a').attr('href', url)
});
</script>
<?php } elseif (qtranxf_getLanguage() == 'en') { ?>
<script>
jQuery(document).ready(function() {
var current_URL = jQuery(location).attr('href');
url = current_URL.replace('/en/', '/ar/')
jQuery('.languages-selection ul li a').attr('href', url)
});
</script>
<?php } ?>

https://qtranslatexteam.wordpress.com/faq/
For example, to show flag only in the top language menu item, enter #qtransLangSw?title=none, if in addition to this current language is not needed to be shown, enter #qtransLangSw?title=none&current=hidden, and so on.

Related

Extend link field output on Drupal Twig Template

I'm trying to figure out how to extend a common Link Field in Drupal 8 with an HTML entity (like »).
My first try was a preprocess function for the field. Unfortunately I didn't manage to set the html option of the link to true
Here's how I tried it
function MYTHEME_preprocess_field(&$variables) {
if ($variables['element']['#field_name'] == 'field_slideshow_link'){
foreach ($variables['items'] as $idx => $item) {
$variables['items'][$idx]['content']['#title'] = $variables['items'][$idx]['content']['#title'] . " <span>»</span>";
$variables['items'][$idx]['content']['#url']->setOption('html', true);
}
}
}
This didn't work. So the only solution I came up with was to manually generate a Link within the template. With just doesn't feel right. Here's how I did it
{{ node.field_slideshow_link.0.title }} <span>»</span>
Has anyone an idea how to solve this problem more elegantly?
Had trouble with this too. Found the following solution
$url = [
'#title' => new FormattableMarkup('&#text;', ['#text' => t('raquo')]);
//The rest
];
Did this with html elements like span so not sure if it will work with this. Let me know!

Drupal 7 Views custom view template fields

I've successfully created a custom view template for my Drupal 7 site but am having issues adding attributes to the content which is outputted. I've searched high and low for the answer to this but to no avail.
I have a view called: views-view-fields--homepage-articles.tpl.php
I am printing content like :
$fields['title']->content
This is fine and expected, and outputs:
Title
But I want to add classes to it - how? I'm thinking I need to write a hook, but I cannot find this documented anywhere. At the moment my solution is a string replace:
<?php print str_replace('<a ', '<a class="brand-blue uppercase nodecoration"', $fields['title']->content); ?>
As you can imagine, this is not a satisfactory or long-term solution.
Many thanks!
You should be able to add the classes to the field using template_preprocess_views_view_fields().
Edit: Couldn't do it the way I thought, but you can overwrite the output of the field like so:
function MY_THEME_preprocess_views_view_fields(&$vars) {
$view = $vars['view'];
if ($view->name == 'node_listing') {
foreach ($vars['fields'] as $id => $field) {
if ($id == 'title') {
$field_output = l($view->result[$view->row_index]->node_title, 'node/'. $view->result[$view->row_index]->nid, array('attributes' => array('class' => 'brand-blue uppercase nodecoration')));
$vars['fields'][$id]->content = $field_output;
}
}
}
}
Have you tried using Semantic Views? https://drupal.org/project/semanticviews - that way you can override the classes within the UI instead of template files, may suit your needs better.

Insert code right after body tag using theme functions

I am trying to add a piece of code at the begining of every page in a Drupal site.
Since I have more than one page template, I want to do this programatically... but am not succeeding.
I am still new and, though I get the gist of hooks, theme functions, and the such, I just can't figure the correct way to achieve this.
So far I've overriden the theme_preprocess_page(&$vars) to add the necessary css and js:
function mytheme_preprocess_page(&$vars) {
if(condition) {
drupal_add_js(drupal_get_path('module', 'mymodule').'/js/modal.js');
}
}
How can I now add html code in every drupal page, preferably just after the opening bodytag or in any other starting section, via a function in the template.phpfile?
Thank you
In your preprocess function, any variable set, will be available in your page.tpl.php file.
function mytheme_preprocess_page(&$vars) {
if (condition) {
$vars['foo'] = '<div id="bar">TEST</div>';
}
}
then, in your page templates:
<body>
<?php print !empty($foo) ? $foo : ''; ?>
...
Had a look at https://www.drupal.org/project/google_tag. This is how they did it:
/**
* Implements hook_page_alter().
*
* Adds a post_render callback
*/
function MYMODULE_page_alter(&$page) {
$page['#post_render'][] = 'MYMODULE_CALLBACK';
}
/**
* Implements callback_post_render().
*
* Inserts JavaScript snippet immediately following the opening body tag.
*/
function MYMODULE_CALLBACK(&$children, $elements) {
$script = '<script type="text/javascript">console.log(\'hello world\');</script>';
// Insert snippet after the opening body tag.
$children = preg_replace('#<body[^>]*>#', '$0' . $script, $children, 1);
return $children;
}
This should keep you from having to modify any code in your templates:
function MY_MODULE_page_build(&$page)
{
$page['page_bottom']['my-markup'] = array('#markup' => '<div>My Markup Here</div>');
}
My approach finally was overriding the first rendered block in the page, in my case the Language Switcher.
Since I already was overriding it to customize it, it wasn't too much of a big deal, but it is anyway an ugly way to achieve that.
<?php
function mytheme_languageswitcher($links) {
// inserting this here like a virus in a dna strip
if(condition) {
drupal_add_js(drupal_get_path('module', 'mymodule').'/js/modal.js');
}
// the *real* code for the language switcher override
}
?>
Since the Language Switcher is rendered in every page, it works. The day the language switcher stops being displayed for whatever reason, this solution will FAIL.
You can add it to the footer with an option passed into the drupal_add_js function.
function THEMENAME_preprocess_page(&$variables) {
if (condition) {
drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/PATH/TO/FILE.js', array('scope' => 'footer'));
}
}
This will end up printing just before the closing body tag via the $page_bottom variable in the template html.tpl.php.
Another way to do it is to use the native drupal methods drupal_add_js and drupal_get_js.
// first, add your JS with a custom "scope" (before process phase)
<?php
drupal_add_js($tag_js, array(
'type' => 'inline',
'group' => JS_GROUP_TAGS,
'every_page' => TRUE,
'scope' => 'body_start',
'weight' => 1,
));
?>
// ugly way : add the drupal_get_js directly into html.tpl.php (but for testing, it's useful):
<body>
<?php print drupal_get_js('body_start'); ?>
...
</body>
// A cleaner way : use an intermediate variable, in a process method
// Exactly like template_process_html, in theme.inc
<?php
function MYMODULEORTHEME_process_html(&$variables){
$variables['js_body_start'] .= drupal_get_js('body_start');
}
?>
Enjoy :)

Dynamic shortcodes and functions in WordPress

I am having a bit of an issue with autogenerating shortcodes, based on database entries.
I am able to get a normal shortcode working i.e:
function route_sc5() {
return "<div>Route 5</div>";
}
add_shortcode('route 5','route_sc');
and the following shortcode to activate it would be [route 5]
This works. But what I need is the shortcode to be produced for each database entry. something like:
$routes = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_routes") );
foreach($routes as $route)
{
function route_sc$route->id () {
return "<div>Route $route->id</div>";
}
add_shortcode('route $route->id','route_sc$route->id');
}
The above is just an example of how I want it to work. Not literally the code I am using. How would I go about achieving this? ):
Thanks.
Here's an example of dynamic shortcode callbacks using PHP 5.3 anonymous functions:
for( $i = 1; $i <= 5; $i++ ) {
$cb = function() use ($i) {
return "<div>Route $i</div>";
};
add_shortcode( "route $i", $cb );
}
I have to ask, though: can you just accomplish what you need to do using shortcode arguments? ie. [route num=3]. Then you could just have one handle_route() function and one [route] shortcode, which may simplify things.
Also, while technically you can include a shortcode with a space in the name, I think it creates a confusing ambiguity. If you decide you need specific shortcodes for each route, I would recommend "route5" or "route-5" rather than "route 5."
Thanks guys, finally got it working. here is the code for any1 who may need it in the future:
function route_sc($atts, $content = null) {
extract(shortcode_atts(array(
'num' => '',
'bg' => '',
'text' => '',
), $atts));
global $wpdb;
$bus = $wpdb->get_row( $wpdb->prepare("SELECT * FROM wp_route WHERE id = '$num'") );
return "<div class='".$bus->text_colour."' style='background-color:".$bus->bg_colour."'>".$bus->route_id."</div></div>";
}
add_shortcode('route','route_sc');
with the shortcode at [route num="5a"]
Dynamic function names are not possible in PHP.
But you could try eval.
eval('function route_sc'.$route->id.' () { return "<div>Route '.$route->id.'</div>"; }');
Go about it a different way: Shortcodes can take parameters. So instead of [route 5] do [route rt="5"]. This way your shortcode processing function stays generic and the part that changes is meant to be dynamic. It also means that if an unexpected shortcode is encountered during the page load you can handle it properly instead of WordPress just stripping the code and replacing it with nothing.
See here for more info: http://codex.wordpress.org/Shortcode_API

wordpress extended_valid_elements for script tag?

Can someone tell me how to tell Wordpress' tinymce editor to NOT strip out script tags? I looked in wp-admin/includes/post.php and added
'extended_valid_elements'=>'script[charset|defer|language|src|type]',
to the $initArray.
When I do a view source on the CMS post editor, I see that it does show up like so:
<script type="text/javascript">
/* <![CDATA[ */
tinyMCEPreInit = {
base : "http://dev.esolar.ca/wp-includes/js/tinymce",
suffix : "",
query : "ver=327-1235",
mceInit : {
mode:"specific_textareas",
editor_selector:"theEditor",
width:"100%",
theme:"advanced",
skin:"wp_theme",
theme_advanced_buttons1:"bold,italic,strikethrough,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,|,link,unlink,wp_more,|,spellchecker,fullscreen,wp_adv",
theme_advanced_buttons2:"formatselect,underline,justifyfull,forecolor,|,pastetext,pasteword,removeformat,|,charmap,|,outdent,indent,|,undo,redo,wp_help",
theme_advanced_buttons3:"",
theme_advanced_buttons4:"",
language:"en",
spellchecker_languages:"+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv",
theme_advanced_toolbar_location:"top",
theme_advanced_toolbar_align:"left",
theme_advanced_statusbar_location:"bottom",
theme_advanced_resizing:"1",
theme_advanced_resize_horizontal:"",
dialog_type:"modal",
relative_urls:"",
remove_script_host:"",
convert_urls:"",
apply_source_formatting:"",
remove_linebreaks:"1",
gecko_spellcheck:"1",
entities:"38,amp,60,lt,62,gt",
accessibility_focus:"1",
tabfocus_elements:"major-publishing-actions",
media_strict:"",
paste_remove_styles:"1",
paste_remove_spans:"1",
paste_strip_class_attributes:"all",
wpeditimage_disable_captions:"",
plugins:"safari,inlinepopups,spellchecker,paste,wordpress,media,fullscreen,wpeditimage,wpgallery,tabfocus"
},
load_ext : function(url,lang){
var sl=tinymce.ScriptLoader;
sl.markDone(url+'/langs/'+lang+'.js');
sl.markDone(url+'/langs/'+lang+'_dlg.js');
}
};
/* ]]> */
</script>
But for some reason ,my editor still doesn't save <script> tags. What am I doing wrong?
It's down to KSES filtering before your post is saved in the DB.
In your theme's functions.php, globalise the variable $allowedpostags, then add the tags you want to allow like so;
global $allowedposttags;
$allowedposttags['script'] = array(
'type' => array(),
'src' => array()
);
Note the structure of the array, and the fact you have to specify the allowed attributes too.
I had a similar problem with iframes. I think instead of <script attributes>, it might be [script attributes]. You'll have to look up the syntax

Resources