Shortcode output shown at the top of the page - php

I know this question is similar to other questions that have been posted. I have followed exactly what was suggested in answers to those questions but still can't figure out why the output is shown at the the top of the page.
function foo_shortcode($atts, $content = null) {
$datashortcode = '<div>'.(function_exists('rtb_kk') ? rtb_kk() : '').'</div>';
return $datashortcode;
}
add_shortcode('showfoo', 'foo_shortcode');
Any idea?

Without knowing how the rtb_kk() function works, I can only assume it uses echo to display content rather than using return. This is what causes the output of that function to appear at the top of the page.
To work around this issue, you can capture the output of the function with ob_start() and ob_get_clean():
function foo_shortcode($atts, $content = null) {
if (function_exists('rtb_kk')) {
// Start output buffering
ob_start();
// Run the function
rtb_kk();
// Capture buffer as a string
$output = ob_get_clean();
} else {
// Function doesn't exist so we return an empty string
$output = '';
}
return '<div>' . $output . '</div>';
}
add_shortcode('showfoo', 'foo_shortcode');
Alternative method
If you're able to use the bcn_display() instead of the rtb_kk() method you're using, then there is no need to rely on ob_get_clean().
function foo_shortcode($atts, $content = null) {
if (function_exists('bcn_display')) {
// Return the output as a string so we can control when it's displayed
$output = bcn_display( true );
} else {
// Function doesn't exist so we return an empty string
$output = '';
}
return '<div>' . $output . '</div>';
}
add_shortcode('showfoo', 'foo_shortcode');

This will solve your problem, just try
<script type="text/javascript">
function foo_shortcode($atts, $content = null) {
if(function_exists('rtb_kk')){
$rtb_kk = rtb_kk();
}else{
$rtb_kk = '';
}
$datashortcode = "<div>$rtb_kk</div>";
return $datashortcode;
}
add_shortcode('showfoo', 'foo_shortcode');
</script>

Related

Why Re-Arranging Code Outputs Differently?

Good Day,
Below I have provided 2 codes, which I did not write but grabbed from a forum. I really need to learn the solution to this new mystery. Both make use of the urlencode(). They are nearly the same code.
I notice that, only the 1st code's output is normal and not encoded while the 2nd one's output is encoded. Why ?
Since both are making use of the urlencode() then shouldn't both their outputs be in encoded format ? This has been greatly puzzling me for days now. I give-up. What's the mystery behind this ?
1st Code:
$url = 'http://nogdog.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=12';
echo prepare_url($url) . "\n";
function prepare_url($url) {
$url_parts = parse_url($url);
if($url_parts === false or empty($url_parts['host'])) {
return false;
}
$url_out = preg_match('/^https?/i', $url_parts['scheme']) ? strtolower($url_parts['scheme']) : 'https';
$url_out .= "://{$url_parts['host']}{$url_parts['path']}";
if(!empty($url_parts['query'])) {
parse_str($url_parts['query'], $query_parts);
foreach($query_parts as $q_key => $q_value) {
$query_string_parts[] = urlencode($q_key).'='.urlencode($q_value);
}
$url_out .= '?'.implode('&', $query_string_parts);
}
return $url_out;
}
2nd Code:
function prepare_url2($url) {
$url_parts = parse_url($url);
if($url_parts === false or empty($url_parts['host'])) {
return false;
}
// re-assemble the start of url string
$url_start = preg_match('/^https?/i', $url_parts['scheme']) ? strtolower($url_parts['scheme']) : 'https';
$url_start .= "://{$url_parts['host']}{$url_parts['path']}";
// rawurlencode the start of url string
$url_out = rawurlencode($url_start);
if(!empty($url_parts['query'])) {
parse_str($url_parts['query'], $query_parts);
foreach($query_parts as $q_key => $q_value) {
// assemble and check if value is numeric
$query_string_parts[] = urlencode($q_key).'='.(is_numeric($q_value) ? intval($q_value) :urlencode($q_value));
}
$url_out .= '?'.implode('&', $query_string_parts);
}
return $url_out;
}
$url = 'http://zorg.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
echo prepare_url2($url);
NOTE
The difference between the two codes are that, the 1st one defines the $url and calls the prepare_url() function at the top. (Before the prepare_url() function's code).
$url = 'http://nogdog.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=12';
echo prepare_url($url) . "\n";
While, the 2nd one defines the $url and calls the prepare_url() function at the bottom. (After the prepare_url() function's code).
$url = 'http://zorg.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
echo prepare_url($url);
Apart from that, both codes are the same.
So, if both the codes are the same (so to speak), then why does the 1st code output like this:
http://nogdog.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=12
And, why does the 2nd code output like this:
http%3A%2F%2Fzorg.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13

Calling a method inside of a method while both are in the same PHP class

I assume this is possible with PHP but I am having some trouble getting it to work. I am trying to minimize the amount of code that is being duplicated by creating only one instance of the html that is supposed to display inside of a php class method. This is the part I only want to create once.
public function display($dbCon){
$content = $obj->content;
$contentSEO = $obj->contentSEO;
$contentLink = $obj->contentLink;
if(!empty($content) && !empty($contentSEO) && !empty($contentLink)){
$content = str_replace("$contentSEO","<small>$contentSEO</small>",$content);
printf("%s", $content);
} elseif(!empty($content) && empty($contentSEO) && !empty($contentLink)){
$content = str_replace("$content","$content",$content);
printf("%s", $content);
} elseif(!empty($content) && !empty($contentSEO) && empty($contentLink)){
$content = str_replace("$contentSEO","<small>$contentSEO</small>",$content);
printf("%s", $content);
} elseif(!empty($content) && empty($contentSEO) && empty($contentLink)){
printf("%s", $content);
} else {
echo "Error";
}
}
Now this is inside of a class and I want the following method to call on this one above after the sql query is performed. The goal with my intent here is that in case I need to call on a similar function with the same HTML, I can simply just call on this one already created instead of coding it all over again. The second portion looks like this.
public function content1($dbCon){
if($res = $this->dbConnection->query("SELECT * FROM content WHERE status = '1' and id = '1'")) {
while($obj = $res->fetch_object()) {
$this->display($dbCon);
}
}
}
Now the simple way would be to simply add them both in the same function and this does work. like the example below.
public function content1($dbCon){
if($res = $this->dbConnection->query("SELECT * FROM content WHERE status = '1' and id = '1'")) {
while($obj = $res->fetch_object()) {
$content = $obj->content;
$contentSEO = $obj->contentSEO;
$contentLink = $obj->contentLink;
if(!empty($content) && !empty($contentSEO) && !empty($contentLink)){
$content = str_replace("$contentSEO","<small>$contentSEO</small>",$content);
printf("%s", $content);
} elseif(!empty($content) && empty($contentSEO) && !empty($contentLink)){
$content = str_replace("$content","$content",$content);
printf("%s", $content);
} elseif(!empty($content) && !empty($contentSEO) && empty($contentLink)){
$content = str_replace("$contentSEO","<small>$contentSEO</small>",$content);
printf("%s", $content);
} elseif(!empty($content) && empty($contentSEO) && empty($contentLink)){
printf("%s", $content);
} else {
echo "Error";
}
}
}
}
However, doing it this way would require me to always copy and paste the same code. when it is needed. I rather just create the function with the query and call on the if statement function to display the HTML. I thought I could simply call it like so inside of the function right after the while statement like so:
$this->display($dbCon);
But instead I keep getting the same error message I planted in the code in case it didn't work. Any help with this would be greatly appreciated.
I think it's because you need to call $this->display($obj); instead of $this->display($dbCon);.

Correct syntax to either pass a variable into an object or modify object to include preg_replace

Apologies if the title is not correctly worded but I can currently output what I am after with:-
$noescape = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($this->_queryText));
And then by var dumping the following:-
$noescape
The final output in the existing function is:-
return $this->_queryText;
I need to modify _queryText to use either $noescape or include the preg_replace above...
I'm unsure whether I can syntactically modify return $this->_queryText; along the lines of:-
return $this->preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($this->_queryText));
or
return $noescape($this->_queryText);
Or whether I'd need to look at modifying another section of the function (entire function below):-
/**
* Retrieve search query text
*
* #return string
*/
public function getQueryText()
{
if (!isset($this->_queryText)) {
$this->_queryText = $this->_getRequest()->getParam($this->getQueryParamName());
if ($this->_queryText === null) {
$this->_queryText = '';
} else {
/* #var $stringHelper Mage_Core_Helper_String */
$stringHelper = Mage::helper('core/string');
$this->_queryText = is_array($this->_queryText) ? ''
: $stringHelper->cleanString(trim($this->_queryText));
$noescape = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($this->_queryText));
echo '<span style="display: none;">';
echo '<pre>';
var_dump (
//$this->rawurldecode($this->getQueryText())
$noescape
);
echo '</pre>';
echo '</span>';
$maxQueryLength = $this->getMaxQueryLength();
if ($maxQueryLength !== '' && $stringHelper->strlen($this->_queryText) > $maxQueryLength) {
$this->_queryText = $stringHelper->substr($this->_queryText, 0, $maxQueryLength);
$this->_isMaxLength = true;
}
}
}
return $this->_queryText;
//return $this->preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($this->_queryText));
//return $noescape($this->_queryText);
}
Hope that makes sense...
Okay, someone else has managed to point this out for me now...
return $this->_queryText = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($this->_queryText));
Working perfectly.

How to convert Meters to Foot using PHP

I have used this code which shows an error:ie if my meters is 175m but when i convert it does'nt show that thing
<?php
function metersToFeetInches($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
$data = $valFeet."′".$valInches."″";
if($echo == true)
{
echo $data;
} else {
return $data;
}
}
?>
<?php
$feetInches = metersToFeetInches(1.75,false);
echo $feetInches;
?>
This is one of those things you can easily find on Google, but I guess you didn't look further than the first link.
Anyways, you should do it like this.
<?php
function metersToFeet($meters) {
return floatval($meters) * 3.2808399;
}
?>
But why is this better than the code you posted? Well, functions are not supposed to do everything. You should write a function for a certain action, not one big function with everything you can every need. Because if you need to add something to that function or change the order of actions, it's a hell of a lot of work.
Furthermore, your function has an option $echo. But why would you need that? You can add such an option to every function, but PHP has a nice commando for that: echo. So instead, it's way better to write echo metersToFeet(10). Or $value = metersToFeet(10) if you need to save the result in a variable.
<?php
function metersToFeetInches($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
$data = $valFeet."′".$valInches."″";
if($echo == true)
{
echo $data;
} else {
return $data;
}
}
?>

php regex failed, why?

The value is AbcDefg_123.
Here is the regex:
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
Should allow a-zA-Z0-9.:_-/ and space in any order or format and does need all but at least one character.
EDIT: Sorry again, looks like var_dump() is my new best friend. I'm working with XML and it's passing the tag as well as the value.
#SilentGhost thnx for the tips.
It works for me too.
<?php
class RegexValidator
{
public function IsAlphaNumeric($alphanumeric)
{
return preg_match('/^[\w. \/:_-]+$/', $alphanumeric);
}
}
?>
and this is how I am testing it.
<?php
require_once('Classes/Utility.php');
$regexVal = new RegexValidator();
$list = array("abcd", "009aaa", "%%%%", "0000(", "aaaa7775aaa", "$$$$0099aaa", "kkdkdk", "aaaaa", "..0000", " ");
foreach($list as $value)
{
if($regexVal->IsAlphaNumeric($value))
{
echo $value . " ------>passed";
echo "<BR>";
}
else
{
echo $value . "------>failed";
echo "<br>";
}
}
?>
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[A-Za-z0-9\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
print checkAlphNum("AbcDefg_123");
Returns true.

Categories