Functions in multi-line variables - php

I'm trying to create af multi-line variable and echo out its contents. I have a couple of functions concatenated to the string and for some reason these get output before all of the other html.
/***SNIP***/
$reference[0] = '
<div class="slide">
<div class="reference-image">
</div>
<div class="reference-text">
<h2 class="reference-title">' . the_title() . '</h2>
<div class="reference-content">
' . the_content() . '
</div>
</div>
</div>
---
';
echo $reference[0];
/***SNIP***/
The html this outputs would be:
the_title
the_content
<div class="slide">
<div class="reference-image">
</div>
<div class="reference-text">
<h2 class="reference-title"></h2>
<div class="reference-content">
</div>
</div>
</div>
---

Wordpress (somewhat annoyingly, in my opinion) doesn't return values from the_title() and the_content().
Instead, it echos (writes to the output stream) the value directly, which is why you can't concatinate it to your string. If you want to return the value instead, use the WP functions:
get_the_content()
and
get_the_title()

Related

Use html in a php variable

I have this variable in php with html, but it doesn't work. Can you guys find any mistake...I tried and didn't find anything.
The code is:
$html .= '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="box-produtos">
<a href="' . $url_imagem . '" class="magnifier" rel="shadowbox">
<img src="' . $url_imagem . '" class="img-responsive img-produtos center-block" onerror="imgError(this);">
</a>
<div class="facebook-btn" onclick="window.open("http://www.facebook.com/sharer/sharer.php?u=' . $base_url . '"/facebookPublish.php?idproduto="' . $idproduto . '", "sharer", "toolbar=0,status=0,width=548,height=325");"><i class="fa fa-facebook fc-facebook"></i>' . $lang["FACEBOOK_SHARE"] . '</div>
<div class="clearfix"></div>
<h5 class="prod-size">' . $produto . '<br>' . $refproduto . '</h5>
<div class="clearfix"></div>
<h5 class="text-center font-color">' . $lang['DEFAULT_PRICE'] . ' ' . $preco . ' €</h5>
' . $lang['GERAL_COMPRAR'] . '';
You can use Heredocs to mix PHP with HTML in pretty way.
$html .= <<< HTML
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="box-produtos">
<a href="{$url_imagem}" class="magnifier" rel="shadowbox">
<img src="{$url_imagem}" class="img-responsive img-produtos center-block" onerror="imgError(this);">
</a>
<div class="facebook-btn" onclick="window.open("http://www.facebook.com/sharer/sharer.php?u={$base_url}/facebookPublish.php?idproduto={$idproduto}", "sharer", "toolbar=0,status=0,width=548,height=325");">
<i class="fa fa-facebook fc-facebook"></i>{$lang["FACEBOOK_SHARE"]}
</div>
<div class="clearfix"></div>
<a href="{$base_url}/{$langi}/produtosDesc/{$idproduto}">
<h5 class="prod-size">{$produto}<br/>{$refproduto}</h5>
</a>
<div class="clearfix"></div>
<h5 class="text-center font-color">
{$lang['DEFAULT_PRICE']} {$preco} €
</h5>
<a href="{$base_url}/{$langi}/produtosDesc/{$idproduto}" class="btn btn-skin center-block btn-prod">
{$lang['GERAL_COMPRAR']}
</a>
HTML;// no indentation, must be single in line, so remove this comment
Also you were messing with facebook link in onclick attribute.
If you want to avoid the mistakes of quotes you can try something like this :
$var="variables";
$html =<<<HTML
<h1>All your html code</h1>
<p>with all your $var or {$var}</p>
HTML;
echo $html;
it's safer.
Use <?php ?> whenever specifying the php variable.
You cannot spread a string over multiple lines. (Justinas sais you can. See comment below)
I think this question is related to your one:
Best Practices: working with long, multiline strings in PHP?
Edit 1:
I think an other solution could also be that you have your HTML in a separate file an then read its content to your variable.
$html .= file_get_contents("your-file.html");
Edit 2: Removed wrong statement. As mentioned in Justinas comment.

Declare inline background image in functions.php

I'm not sure if this can be done as I cannot find anything to help me anywhere no matter how hard i try. I'm using Ajax to load to in posts on the press of the button. the posts that are loaded in are formatted by my function inside my functions.php. That all works perfetly,the issue i'm having is the background-image: property needs to be inline css so that it can pull the image from my custom field. This all works perfectly in the template file, however. no matter what I try the functions.php rejects my inline style for background image no matter what I try.
Here's my If statement in it's entirety:
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
if ($_SESSION["load_type"] == 'home')
{
$out .= '<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe">
'.get_the_post_thumbnail( get_the_ID(), $size, $attr ).'
<figcaption>
<h2>'.get_the_title().'</h2>
<hr class="light">
<p class="description">'.get_the_content().'</p>
</figcaption>
</figure>
</div>
</div>';
}
else
if ($_SESSION["load_type"] == 'category')
{
$out .= '<div class="small-6 large-6 columns end thumb under">
<div id="case">
<div class="th" id="element" >
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
</div>
<div class="brief">
'.get_the_title().'
<p class="suppy">Supplier</p>
<p>'.get_the_excerpt().'</p>
<a class="more-btn" href="'. get_permalink($post->ID) .'">More</a>
</div>
</div>';
}
else
if ($_SESSION["load_type"] == 'product')
{
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url(''.the_field(product_image).'')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
endwhile;
endif;
wp_reset_postdata();
die($out);
and heres the part of it that I'm having trouble with and crashes the whole site every time I try to load in a background-image:
if ($_SESSION["load_type"] == 'product')
{
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url(' '.the_field(product-image).' ')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
enter code here
Can anyone see where I'm going wrong?
Change the following
style="background-image: url(' '.the_field(product-image).' ')"
into the
style="background-image: url('.the_field("product-image").')"
This should work if:
Your "product-image" is custom defined size (if its constant use it without quotes) - or edit your question and explain what it is.
the_field() function need to "return" value and not to echo it. I am mentioning this because by wordpress codex usually use "the_something()" function will not return value, it will just display something. If you want to to return a value it is usually "get_the_something()". It is important because it will break your json object (if that is what you are using on js side)
Example: the_content() vs get_the_content(), or get_the_title() vs the_title() etc...
Quotes within background-image should be optional by this.
if ($_SESSION["load_type"] == 'product'){
$image = the_field(product_image);
$out .= '<div class="small-6 large-3 columns">
<div class="small-6 large-12 columns end no-pad morepro" style="background-image: url('"'.$image.'"')">
<a class="fill-div" href="'. get_permalink($post->ID) .'"></a>
</div>
<h2 class="product-load">'.get_the_title().'</h2>
</div>';
}
and see if it works

Use of undefined constant

Hi I have this error in my website
my website is wordpress 4
i use post format
in post format i create this php to if page has quote post then dont load title and image and etc from quote post just show quote content is meta box (wordpress)
Notice: Use of undefined constant quote - assumed 'quote' in C:\xampp\htdocs\personal\wp-content\themes\personal\warp\systems\wordpress\layouts\_post.php on line 4
and
Notice: Use of undefined constant quote - assumed 'quote' in C:\xampp\htdocs\personal\wp-content\themes\personal\warp\systems\wordpress\layouts\_post.php on line 14
this is _post.php code in bellow
<?php $format = get_post_format(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('group'); ?>>
<?php
if ($format != quote ) {
$css_class = "b-box";
} else {
$css_class = "q-box";
}
echo "<div class=\"$css_class\">";
?>
<?php get_template_part('inc/post-formats'); ?>
<?php if ($format != quote ) : ?>
<div class="post-content">
<div class="blog-img-box">
<img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" />
</div>
<div class="post-deco blog-icon-box">
<div class="hex hex-small">
<i class="fa blog-icon"></i>
<?php if ( $format != false ) :?><?php endif; ?>
</div>
</div><!--/.post-deco-->
<h2 class="blog-title">
<?php the_title(); ?>
</h2><!--/.post-title-->
<div class="blog-details row">
<div class="col-md-4"><i class="fa fa-calendar blog-details-icons"></i>
<p class="blog-details-icons-txt"><?php the_time('j M, Y'); ?></p>
</div>
<div class="col-md-4">
<a href="<?php comments_link(); ?>">
<i class="fa fa-comment blog-details-icons"></i>
<p class="blog-details-icons-txt"><?php comments_number( '0', '1', '%' ); ?> Comments</p></a>
</div>
<div class="col-md-4"><i class="fa fa-eye blog-details-icons"></i>
<p class="blog-details-icons-txt"><?php echo getPostViews(get_the_ID()); ?></p>
</div>
<div class="likes"><i class="fa fa-heart blog-details-icons"></i>
<p class="blog-details-icons-txt">18</p>
</div>
</div>
<div class="blog-txt">
<?php the_excerpt(); ?>
</div>
<div class="readmore-box"><p class="readmore-txt"><?php _e('Read More','anew'); ?></p></div>
</div><!--/.post-content-->
<?php endif ?>
</div><!--/.post-inner-->
</article><!--/.post-->
please check and say to me what i wrong
thank you !
If you want to use the quote as a literal string (line 4), not a variable name, you must enclose it into single or double quote characters (' or "). Otherwise, PHP thinks that you're referencing a PHP constant.
For reasons of backward compatibility, PHP falls back on using the string as literal, but it does throw an E_NOTICE error – the one you're experiencing.
verify that all variables have this sign $
correct variable $test
incorrect variable test

PHP multiline string with PHP

I need to echo a lot of PHP and HTML.
I already tried the obvious, but it's not working:
<?php echo '
<?php if ( has_post_thumbnail() ) { ?>
<div class="gridly-image"><?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) ));?>
</div>
<?php } ?>
<div class="date">
<span class="day">
<?php the_time('d') ?></span>
<div class="holder">
<span class="month">
<?php the_time('M') ?></span>
<span class="year">
<?php the_time('Y') ?></span>
</div>
</div>
<?php } ?>';
?>
How can I do it?
You don't need to output php tags:
<?php
if ( has_post_thumbnail() )
{
echo '<div class="gridly-image">'. the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )) .'</div>';
}
echo '<div class="date">
<span class="day">'. the_time('d') .'</span>
<div class="holder">
<span class="month">'. the_time('M') .'</span>
<span class="year">'. the_time('Y') .'</span>
</div>
</div>';
?>
You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.
If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:
<?php
$var = 'Howdy';
echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well
and now the output ends
EOL;
Use Heredocs to output muli-line strings containing variables. The syntax is...
$string = <<<HEREDOC
string stuff here
HEREDOC;
The "HEREDOC" part is like the quotes, and can be anything you want. The end tag must be the only thing on it's line i.e. no whitespace before or after, and must end in a colon. For more info check out the manual.
Use the colon notation
Another option would be to use the if with a colon (:) and an endif instead of the brackets:
<?php if ( has_post_thumbnail() ): ?>
<div class="gridly-image">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('summary-image', array('class' => 'overlay', 'title'=> the_title('Read Article ',' now',false) )); ?>
</a>
</div>
<?php endif; ?>
<div class="date">
<span class="day"><?php the_time('d'); ?></span>
<div class="holder">
<span class="month"><?php the_time('M'); ?></span>
<span class="year"><?php the_time('Y'); ?></span>
</div>
</div>
The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:
$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';
To do that, you must remove all ' charachters in your string or use an escape character. Like:
<?php
echo '<?php
echo \'hello world\';
?>';
?>
Use the show_source(); function of PHP. Check for more details in show_source. This is a better method I guess.

omit a div if its null

I have a div that looks like this:
<div id="restinfoinn">
<div id="resthead">Purpose</div>
<div id="restcontstitle2"><?php echo $row_pages_here['purpose']; ?></div>
</div>
I want it to be omitted if the value of purpose is empty/null. How can I do this?
<?php if (!empty($row_pages_here['purpose'])) : ?>
<div id="restinfoinn">
<div id="resthead">Purpose</div>
<div id="restcontstitle2"><?php echo $row_pages_here['purpose']; ?></div>
</div>
<?php endif; ?>
But i think it would be better to print the empty div and deal with the design in CSS
This is really basic. You just need to do an IF check on top.
<?php if (!empty($row_pages_here['purpose'])) : ?>
<div id="restinfoinn">
<div id="resthead">Purpose</div>
<div id="restcontstitle2"><?php echo $row_pages_here['purpose']; ?></div>
</div>
<?php endif;?>
Have a look at alternative control syntax and empty

Categories