Reputation: 3
I'm trying to put a Polylang language switcher in PHP to appear in the header of a webpage with a shortcode. I get the switcher where I insert the shortcode, but also appears at the top of the webpage. It seems that it prints twice. I'm doing something wrong, but I don't know what it is.
<?php
function switcher() {
$message = pll_the_languages( array( 'hide_current' => 1 ) );
return $message;
}
add_shortcode( 'switcher_shortcode', 'switcher' );
?>
My guess is that this line pll_the_languages( array( 'hide_current' => 1 ) )
prints the first switcher and the "return" prints the second switcher. If I delete the return
the switcher only appears at the top of the webpage, but I need the switcher where I put the shortcode.
Upvotes: 0
Views: 32
Reputation: 16
From what I could see, the function pll_the_languages
echoes the output directly instead of returning it. That's why, as you stated, it also appears at the top of the page.
If you don't want that to happen again, what you should do is use output buffering.
Example:
<?php
function switcher() {
ob_start(); // Start output buffering
pll_the_languages( array( 'hide_current' => 1 ) ); // This prints the switcher
return ob_get_clean(); // Capture the output and return it
}
add_shortcode( 'switcher_shortcode', 'switcher' );
?>
Explanations:
ob_start
: starts buffering the output.pll_the_languages
: prints the language switcher, but doesn't return it.ob_get_clean
: captures the printed output and returns it as a string, preventing it from being displayed twice.Upvotes: 0