OK.
I have a very long and pretty complicated function.
It looks almost like this one:
<?php
function hello() {
echo 'My Function!' ?>
<ul>
<li> Blablabla </li>
<ul>
(...)
<?php } ?>
The HUGE problem here is that I'm UNABLE to echo anything.
My function HAVE to return it's contents instead of echoing or direct outputting (it has to be that way, it's a Wordpress shortcode and when I echo - the contents are getting displayed at the top of the page - ALWAYS, not in the place where I want them):
<?php
function hello() {
$output .= 'My Function!';
$output .= '<ul>';
$output .='<li> Blablabla </li>';
$output .='<ul>';
(...)
return $output;
} ?>
I hope it's easy till now.
Now, the real problems are:
I have tons of direct input code like:
?>
<div>
<span>
<p>Smth</p>
<a>smth</a>
</span>
</div>
<?php
Adding $output everywhere kills the nice paragraphs/whitespace and code is getting VERY HARD to read and understand (and all HTML elements are parts of variable now, so even my php editor is not treating them well and coloring them as PHP elements).
And another thing, I have tons of lines like this one:
<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link">
(yes, this is a single line)
And I have absolutely no idea how to add such lines to $output.
$output .= '<a href="<?php bloginfo('template_directory'); ?>/includes/php/timthumb.php?src=<?php echo $url; ?>&h=<?php if($items=="one") echo 320; elseif($items=="two") echo 230; elseif($items=="three") echo 180; elseif($items=="four") echo 130; ?>&w=<?php if($items=="one") echo 600; elseif($items=="two") echo 420; elseif($items=="three") echo 277; elseif($items=="four") echo 203; ?>" title="<?php the_title(); ?>" class="link"> ';
Doesn't work of course (even with \'s before ' and ").
I believe there MUST be an easier way to attach all the code to return, but how?
I've tried with ob_start(); before code and return ob_get_clean(); after, but it outputs shortcode name instead of contents.
Its very hard to imagine what the problem you are trying to solve here is - although I'm not familiar with wordpress. Can't you just call the function where the output is supposed to go?
You could use output buffering - use echo/print as usual but...
ob_start();
hello();
$output=ob_get_contents();
ob_end_clean();
But that doesn't solve the problem that you still need to send to the browser at the right place in the page - and if you can do:
print $output;
in the right place, then you can surely do:
hello();
in the same place.
I agree with symcbean, but this might be a more practical approach at integrating with Wordpress: if you now have a single function called hello( ) which displays HTML, you might want to consider renaming that function to hello_content( ) (or something similar) and replace the hello( ) function with the suggestion symcbean gave you:
function hello_content( ) {
echo "foo";
}
function hello( ) {
ob_start( );
hello_content( );
return ob_get_clean( );
}
That should fix your immediate issue.
PHP Heredoc syntax will keep things looking neat and tidy and you can return the output to a variable. As long as you don't require any constants it will work fine.
You use it in this fashion:
function bar() {
$var = <<<EOV
anything here
anything there
EOV;
return $var;
}
Related
I have this code
<a href="
?page=<?php echo $_GET['page'] ?>
&tab=<?php echo $_GET['tab'] ?>
&subtab=list"
Nazwa</a>
Chrome renders the above code as this:
?page=nurk-edycja-tresci-home &tab=artykuly &subtab=list
With a lot of whitespaces :C I know a cause comming from my coding style but for me this improves readability a lot. Is there any solution to reconcile my style with browsers? ;)
Keeping the white-space server-side
It also doesn't look like your HTML syntax is valid, you're missing a >
When the PHP is preprocessed, it won't return any of the whitecaps in the code so you should be good:
<a href="<?php
echo '?page' . $_GET['page'];
echo '&tab' . $_GET['tab'];
echo '&subtab=list";
?>">Nazwa</a>
You could also put the whitespace in <?php ?> so the server will process it and then return it to the client
<a href="<?php
?>?page=<?=$_GET['page'] ?><?php
?>&tab=<?=$_GET['tab'] ?><?php
?>&subtab=list"
>Nazwa</a>
You can also replace <?php echo with <?=
How I would do it
<a href="<?= '?page=', $_GET['page'], '&tab', $_GET['tab'], '&subtab=list' ?>">
This syntax is very readable and also let's you put newlines:
<a href="<?=
'?page=', $_GET['page'],
'&tab', $_GET['tab'],
'&subtab=list'
?>">
JavaScript?
If you really like your code right now, you can use JavaScript to get rid of the spaces:
(function () {
window.onload = function () {
var elems = document.getElementsByTagName('a'),
i = 0;
for (; i < elems.length; i += 1) {
elems[i].href = (elems[i].href || '').replace(/\s/g, '');
}
}
}());
Even shorter:
window.onload = function () { Array.prototype.forEach.call(document.getElementsByTagName('a'), function (t) { t.href = (t.href || '').replace(/\s/g, '') }) }
ECMAScript2015 (Harmony):
window.onload = () => Array.from(document.querySelectorAll('a[href]')).map(t => (t.href = a.href.replace(/\s/g, ''));
You can solve it by moving the PHP close tag, (and the opening quote), although it still doesn't look very nice:
<a href=
"?page=<?php echo $_GET['page']
?>&tab=<?php echo $_GET['tab']
?>&subtab=list">
Nazwa</a>
But personally, I would choose to build the url earlier, so you just have to output a small variable in your HTML:
<?php
// I know you can use array items in strings too, but I like to split it up.
$page = $_GET['page'];
$tab = $_GET['tab'];
$url = "?page=$page&tab=$tab&subtab=list";
?>
<a href="<?=$url?>">
Nazwa
</a>
[opinion] I think the last way is better. You have just a simple variable to output, which is constructed somewhere else. This way it's also much easier to move the HTML to a separate template. Such template should contain as little logic as possible and concatting variables should not be there. [/opinion]
i am trying to insert a link in an echoed line,
regular links work, but not this one, cant figure it out what's wrong
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
the_permalink() is a not a return function, it echoes the permalink. Replace it with get_permalink, which returns the permalink.
if($gallery_images != ''){
foreach ($gallery_images as $gallery_image){
$thumb = wp_get_attachment_image_src($gallery_image[SN.'gallery_post_image']['id'], 'post-thumb', false);
echo '<li><a <img src="'.$thumb[0].'" alt="'.$gallery_image[SN.'gallery_post_title'].'" /><p class="flex-caption">'.$gallery_image[SN.'gallery_post_title'].'</p></li>';
}
}
Your first problem is that. You don't include a function on a string that way.
echo '<li><a href="**<?php the_permalink(); ?>**">
Try this:
echo '<li><a href="'.the_permalink().'">
Then
.$gallery_image[SN.'gallery_post_title'].
You got a syntax error there.
SN.'gallery_post_title' // notice SN
It's fine if you define SN though.
Also, why do you have a close curly brace }?
Did you just copy and paste your code here sloppily or is that intentional? It's confusing if it is.
I'm using this to load php functions and send them to javascript in a plugin, like:
function me_nav_query_submit() {
$urlcall = nav_me_paises(); /* fetches a large html string */
$response = json_encode($urlcall); /* encode to display using jQuery */
//header( "Content-Type: application/json" );
echo $response;
exit;
}
I insert the html on the page, using
function(response) {
jQuery('#navcontainer').html(response);
}
and everything works fine, except that i get a "null" string at the very end of the result.
json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn't seem to be the case. I've also tried using utf8_encode() with no success. I've read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append "null" to the end.
note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a "headers already sent" error.
Any ideas?
EDIT this is the function called:
function nav_me_paises() {
?>
<ul class="navcategorias">
<?php $tquery = $_POST['wasClicked']; ?>
<?php $navligas = get_terms($tquery,'hide_empty=0') ?>
<?php foreach ($navligas as $liga) : ?>
<?php $link = get_term_link($liga); ?>
<li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
<?php endforeach; ?>
</ul>
<?php
}
nav_me_paises() is not returning anything. the html block is treated as output!
function nav_me_paises() {
$output = '<ul class="navcategorias">';
$tquery = $_POST['wasClicked'];
$navligas = get_terms($tquery,'hide_empty=0')
foreach ($navligas as $liga) {
$link = get_term_link($liga);
$output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
}
$output .='</ul>';
return $output;
}
nav_me_paises() doesn't return anything. Passing this "nothing" to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it
function foo()
{
};
var_dump(json_encode(foo()));
string(4) "null"
Also, if it's just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.
I presume all you wanna do is put that HTML inside some div, because you'd not parse it into a DOM and process its elements... because if u'd do that u'd not use HTML for it.
For instance, let's say I have a snippet of code, which I'd like to keep separate. for now, we'll call it snippet.php.
snippet.php would be a simple block of reusable HTML which would have php variables in it. Something like this:
<article>
<h1>{$headline}</h1>
<p>${$body}</p>
</article>
I'd like to be able to return this code from a function, along the lines of this:
function writeArticle($headline, $body){
return "contents of snippet.php using the variables passed in to the function"
}
I know I could just use html in a string to return, but the actual snippet would be fairly complex, and I want it to be modular.
One method is using file_get_contents and str_replace
HTML:
<article>
<h1>[-HEADLINE-]</h1>
<p>[-BODY-]</p>
</article>
PHP:
function writeArticle($headline,$body){
$content = file_get_contents("[add your html directory here]/file.html",true);
$content = str_replace("[-HEADLINE-]",$headline,$content);
$content = str_replace("[-BODY-]",$body,$content);
echo $content;
}
You can use output buffering and include the file so the PHP variables get evaluated. However, since you are not using <?php PHP tags ?> you will need to wrap it in HEREDOC format (http://php.net/manual/en/language.types.string.php). Scroll down to Heredoc on the page.
snippet.php
$output = <<<HEREDOC
<article>
<h1>{$headline}</h1>
<p>{$body}</p>
</article>
HEREDOC;
function writeArticle($headline, $body){
ob_start();
include('snippet.php');
$snippet = ob_get_clean();
return $snippet
}
You could do this:
HTML DOCUMENT
Include('blockClass.php');
$block = new blockClass();
echo $bl = $block->block($headline, $body);
CLASS DOCUMENT
class blockClass{
function block($headline, $body){
$var ='<article>
<h1>' . $headline . '</h1>
<p>' . $body . '</p>
</article>';
return $var;
}
}
I had the same question and ended up solving it like this. I feel like this is the cleanest approach. Just turn php on and off within the function.
<?php
function writeArticle($headline, $body){
?>
<article>
<h1><?php echo $headline; ?></h1>
<p><?php echo $body; ?></p>
</article>
<?php
}
?>
writeArticle('foo', 'bar');
I have a php function that generates HTML code like below
function j_uf_SomeFunction($some_var) {
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
}
Of course, its much more advanced and add all sorts of user options.
In most case I place this function inline, as opposed to have to append it to a string. However, I've come to the first occurrence (probably not the last occurrence) where I need to store the rendered HTML in a string and not have it sent straight off to the parser for building the page.
I need to cut the function off and tell it to take the html generated and store it in a string, and not send it off to the page, only on certain situations.
function j_uf_SomeFunction($some_var) {
ob_start();
?><div class="db_photo">
<img alt="<?php echo some_php_function ?>" src="<?php echo $some_var; ?>" />
</div><?php
return ob_get_clean();//suggestion by GWW
}
ob_start() is starting buffer receive
ob_get_clean() cleans current buffer and returns its value.
More info on http://php.net/manual/en/function.ob-start.php
ob * output buffering
It sounds like output buffers are one possible solution to your problem.
You use an output buffer like so:
ob_start();
j_uf_SomeFunction($someVar);
$buffer = ob_get_contents();
ob_end_clean();
The $buffer variable now contains anything printed out by the function.
It's important to always close output buffers with ob_end_clean or ob_end_flush. You can read more here: http://php.net/manual/en/book.outcontrol.php
Regards,
Chris
I don't I have a template system to parse this functions value into... its not your standard function call.
sure you do... its jsut contained within the function :-)
using translation:
function j_uf_SomeFunction($some_var) {
$html = "<div class="db_photo"><img alt="%some_function_result%" src="%some_var%" /></div>";
$tokens = array(
'%some_var%' => $some_var,
'%some_function_call_result%' => some_function_call()
);
return strtr($html, $tokens); // or echo
}
using string manipulation:
function j_uf_SomeFunction($some_var) {
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, some_function_call(), $some_var); //or echo
}
if some_function_call actually outputs html directly with its own echo then jsut use a buffer:
function j_uf_SomeFunction($some_var) {
ob_start();
some_function_call();
$somefunc = ob_get_clean();
$html = '<div class="db_photo"><img alt="%s" src="%s" /></div>';
return sprintf($html, $somefunc, $some_var); //or echo
}