I am using a Wordpress plugin for custom fields.
the_field('something')
is, I pressume, just echoing the return value.
Is it not possible to store that return value into a variable?
because $a = the_field('something'); is also echoing.
What I really want to do is this
if(the_field('something')) {
// echo the_field('something')
}
else
// do something
but either way, it just echoes that thing in the page
As I said in my comment, If a function just echos something, then there is no return value. But there is still a way to capture the output.
Consider this function
function doStuff()
{
echo 'hello';
}
You can't get a return value from that, but you can capture the contents by using the ob_functions:
ob_start();
doStuff();
$output = ob_get_contents();
ob_end_clean();
Now $output contains the output of that function, rather than it having been printed.
WordPress I do not like. It seems that they have two functions (or more) for retrieving about anything. One echos it the_title() and the other returns it get_title(). For this plugin this should work:
if($field = get_field('something')) {
echo $field;
}
else
// do something
}
If you run across something that echos and doesn't return a value and no corresponding function that does return something, then:
ob_start();
the_something();
$output = ob_get_clean();
// use $output
Related
I'm defining a function which can handle shortcodes for users wisiwyg made posts.
Using a function based on preg_replace_callback works great, but the returned replaced values prints before the initial string
This is the handler function
function shortcodify($string){
return preg_replace_callback('#\[\[(.*?)\]\]#', function($matches){
$parts = explode(':',$matches[1]);
$fnName = array_shift($parts);
if(function_exists($fnName)){
return call_user_func_array($fnName,$parts);
} else {
return $matches[0];
}
},$string);
}
This is the function which will replace the shortcode
function slider($tag){
//search $tag in DB
echo '<div>...'.$sliderContentFromDB.'...</div>';
}
The usage:
$postContent = "<h1>Super Slider</h1> [[slider:super-slider]] <p>Slider Description</p>";
shortcodify($postContent);
The expected result is:
<h1>Super Slider</h1>
<div>...super slider content...</div>
<p>Slider Description</p>
The actual result is:
<div>...super slider content...</div>
<h1>Super Slider</h1>
<p>Slider Description</p>
What could I be doing wrong?
You should return the value rather than echoing it. What you're seeing is correct, in that the callback function should evaluate before the preg_replace_callback() result is returned to your variable.
function slider($tag){
//search $tag in DB
return '<div>...'.$sliderContentFromDB.'...</div>';
}
Returning will ensure it gets aggregated into the rest the results from preg_replace_callback(), and returned in the correct order. Example.
This is how I would do it:
function shortcodify($string){
return preg_replace_callback('#\[\[(.*?)\]\]#', function($matches){
//start output buffering
ob_start();
$parts = explode(':',$matches[1]);
$fnName = array_shift($parts);
//echo values in case they return instead of echo
if(function_exists($fnName)){
echo call_user_func_array($fnName,$parts);
} else {
echo $matches[0];
}
//return contents of buffer
return ob_get_clean();
},$string);
}
Now if you return or echo from the shortcode it makes no difference, because in either case it will get swept up by the buffer.
The following function is part of code written into the core of a plugin I am reverse engineering. The problem with it is that I need to do an str_replace on it and I cannot because it is already set to echo.
The function is.
function similar_posts($args = '') {
echo SimilarPosts::execute($args);
}
I call it in my pages using similar_posts(), but what I really need to do in my theme is call $related = similar_posts(), however that function is set to echo. How do I change that.
I tried this.
function get_similar_posts($args = '') {
SimilarPosts::execute($args);
}
But that did not produce any results.
function get_similar_posts($args = '') {
return (SimilarPosts::execute($args));
}
If you want to use the value SimilarPosts::execute ($args) returns, you'll need to use the keyword 'return' inside your get_similar_posts.
function get_similar_posts ($args = '') {
return SimilarPosts::execute($args);
}
If you are unable to change the definition of get_similar_posts there are ways to snatch the content printed by similar_posts even though it's "set to echo".
This can be accompished by using the Output Control Functions available in PHP.
function echo_hello_world () {
echo "hello world";
}
$printed_data = "";
ob_start ();
{
echo_hello_world ();
$printed_data = ob_get_contents ();
}
ob_end_clean ();
echo "echo_hello_world () printed '$printed_data'\n";
output
echo_hello_world () printed 'hello world'
Use return instead of echo.
So that you have:
return SimilarPosts::execute($args);
instead of:
echo SimilarPosts::execute($args);
Wrap the function inside another in which you use output buffering.
Done it..
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
and on the page get_similar_posts();
Should have thought of that.
return from the function:
function get_similar_posts($args = '') {
return SimilarPosts::execute($args);
}
I'm working with some functions that echo output. But I need their return so I can use them in PHP.
This works (seemingly without a hitch) but I wonder, is there a better way?
function getEcho( $function ) {
$getEcho = '';
ob_start();
$function;
$getEcho = ob_get_clean();
return $getEcho;
}
Example:
//some echo function
function myEcho() {
echo '1';
}
//use getEcho to store echo as variable
$myvar = getEcho(myEcho()); // '1'
no, the only way i can think of to "catch" echo-statements it to use output-buffering like you already do. i'm using a very similar function in my code:
function return_echo($func) {
ob_start();
$func;
return ob_get_clean();
}
it's just 2 lines shorter and does exactly the same.
Your first code is correct. Can be shortened though.
function getEcho($function) {
ob_start();
$function;
return ob_get_clean();
}
echo getEcho($function);
Your first piece of code is the only way.
Did you write these functions? You can go 3 ways:
Using your wrapper to do capturing via output buffering.
Extra set of functions calls, wordpress style, so that "somefunc()" does direct output, and "get_somefunc()" returns the output instead
Add an extra parameter to the functions to signal if they should output or return, much like print_r()'s flag.
function getEcho() {
ob_start();
myEcho();
return ob_get_clean();
}
$myvar = getEcho();
This is probably a silly question but how do you extract the value of a variable inside a PHP function? I found this code on stackoverflow on how to find the title of the webpage:
function page_title($url)
{
$fp = file_get_contents($url);
if (!$fp)
return null;
$res = preg_match("/<title>(.*)<\/title>/", $fp, $title_matches);
if (!$res)
return null;
$title = $title_matches[1];
return $title;
}
I have a variable called $extract outside the function above and want to insert the value of $title from the function into the outside variable, $extract. I'm assuming you have to call the function first and then do something else to achieve this but I don't know what that step is.
If I call the function and the variable $title returns the value "welcome to my website", I want to associate that value with the outside variable, $extract.
$extract = page_title($url);
place that outside the function and you should be good to go
You can simply assign the value returned by a function to your property:
$value = somefunc();
echo $value;
function somefunc()
{
return "trendy value";
}
just write
$extract = page_title($url);
Outside your function. i.e. make function call like the above line and returned value whther null or $title will be stored to extract
so I have 2 functions like this:
function boo(){
return "boo";
}
and
function foo(){
echo "foo";
}
the fist one will return a value, and the 2nd one will output something to the screen directly.
$var = boo();
foo();
How can I merge these 2 functions into one, and somehow detect if it's being called to output the result to the screen, or if it's called for getting the return value? Then choose to use return or echo...
function boo_or_foo ($output = false) {
if ($output) {
echo "fbo";
} else {
return "foo";
}
}
But whats the benefit against just using one function (boo()) and echo it yourself?
echo $boo();
Well, a function should only do one thing, so typically you would have two functions. But, if you would like to combine them you can just check if is set:
function boo($var=null){
if(isset($var)) echo $var
else return "boo";
}
well return true in the function that prints then yo just do
function foo(){
echo "foo";
return true;
}
if(foo()){
echo "foo did print something";
}else{
echo "nope foo is broken";
}
I wanted to achieve the same effect. In my case I have functions that produce HTML which I want echoed directly sometimes (when an Ajax call is being made), or returned (when a call is made from another script).
For example, a function that creates a list of HTML <option> elements - listOfOption($filter). When one of my pages is first created, the function is called and the result is echoed in place:
<?= listOfOption($var) ?>
But sometimes the same data needs to be retrieved in an Ajax call:
http://site.com/listOfOption.php?parameter=2
Instead of writing two different scripts or specifying the behaviour in a parameter, I keep listOfOption($filter) in its own file like this:
if (__FILE__ == $_SERVER['SCRIPT_FILENAME'])
{
echo listOfOption($_REQUEST['parameter']);
}
function listOfOption($filter)
{
return '<option value="1">Foo</option>';
}
This way if the call is from another script, it returns the data; otherwise it prints the data.
Note that if a parameter isn't passed to the function I wouldn't have to do this, I could live with echoing the data always and replacing the <?= listOfOption() ?> invocation with <? listOfOption() ?> to keep things clear.