I have an issue where I'm showing boxes of some posts from my database in a foreach loop.
The length of the post title affects the design. For example if one post has a long title next to one with a short title, it will push the link i have below down. This makes it look uneven.
Therefor I'm trying to write a function that checks if the length is too short, it should insert a line break.
This is what I have so far.
function insert_line_break($text){
if (strlen($text) < 10 ) {
echo "<br>";
}
}
<?= insert_line_break($entry["title"]) ?>
However that seems to replace the title with a linebreak.
What am I missing?
You have missed to echo the text itself.
function insert_line_break($text){
if (strlen($text) < 10 ) {
return "<br>";
}
}
<?php echo $entry["title"] . insert_line_break($entry["title"]); ?>
Note:
I changed the function to return a value instead of echoing it to the output, so it will be much more reusable in the future.
And I expanded the short tag <? to <?php and made the = to verbose echo which is much clearer and readable way of coding.
And of course I closed the line with semicolon ; as it should be.
EDIT:
<?php echo $entry["title"] . insert_line_break($entry["title"]); ?>
echo prints the content of $entry["title"] and then ask function insert_line_break($entry["title"]) to decide whether it contains string shorter than 10 characters, if so it returns <br> that is echoed. And that's it.
I'd like to preface that I am not too fluent in php so i'm trying to understand and build php as i go.
I am attempting to add a custom Slidedeck slider to my website, http://cfsb.org/ . I currently have one in the header, but would like to change it on a per page basis.
I currently have:
function slidedecktwo_header_home() {
if (is_home()) {
echo do_shortcode('[SlideDeck2 id=xxx]');
}
}
add_action('genesis_header', 'slidedecktwo_header_home');
But when i try to add something like
else if (is_page(PAGE_ID = x)) {
echo do_shortcode('[SlideDeck2 id=xxx');
}
My webpage crashes and I have to delete the code before my website returns. Anyone see some obvious problems?
Thanks in advance.
Not sure if what you posted is the actual PHP you tried, but there are definite syntax errors.
Your code should look more like this (I added a random ID passed as an integer to the is_page() function):
function slidedecktwo_header_home() {
if ( is_home() ) {
echo do_shortcode('[SlideDeck2 id=xxx]');
} elseif ( is_page(42) ) {
echo do_shortcode('[SlideDeck2 id=xxx]');
}
}
add_action('genesis_header', 'slidedecktwo_header_home');
In your snippet, you had is_page( PAGE_ID = x ) and your shortcode snippet wasn't closed with a closing bracket ]
Are there any differences between...
if ($value) {
}
...and...
if ($value):
endif;
?
They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:
<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
At our company, the preferred way for handling HTML is:
<? if($condition) { ?>
HTML content here
<? } else { ?>
Other HTML content here
<? } ?>
In the end, it really is a matter of choosing one and sticking with it.
They are indeed both the same, functionally.
But if the endif is getting too far from the correspondent if I think it's much better practice to give a referencing comment to it. Just so you can easily find where it was open. No matter what language it is:
if (my_horn_is_red or her_umbrella_is_yellow)
{
// ...
// let's pretend this is a lot of code in the middle
foreach (day in week) {
sing(a_different_song[day]);
}
// ...
} //if my_horn_is_red
That actually applies to any analogous "closing thing"! ;)
Also, in general, editors deal better with curly brackets, in the sense they can point you to where it was open. But even that doesn't make the descriptive comments any less valid.
Here's where you can find it in the official documentation: PHP: Alternative syntax for control structures
I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:
<?php if ( $this->hasIterable ): ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ):?>
<?php for ( $i = 0; $i <= $val; $i++ ): ?>
<li><?php echo $key ?></li>
<?php endfor; ?>
<?php endforeach; ?>
</ul>
<?php elseif ( $this->hasScalar ): ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
<p>Foo = Bar</p>
<?php endfor; ?>
<?php else: ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ): ?>
<p>Spam</p>
<?php else: ?>
<p>Eggs</p>
<?php endif; ?>
<?php endif; ?>
as opposed to:
<?php if ( $this->hasIterable ){ ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ){?>
<?php for ( $i = 0; $i <= $val; $i++ ){ ?>
<li><?php echo $key ?></li>
<?php } ?>
<?php } ?>
</ul>
<?php } elseif ( $this->hasScalar ){ ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
<p>Foo = Bar</p>
<?php } ?>
<?php } else { ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ){ ?>
<p>Spam</p>
<?php } else { ?>
<p>Eggs</p>
<?php } ?>
<?php } ?>
This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.
I think that it really depends on your personal coding style.
If you're used to C++, Javascript, etc., you might feel more comfortable using the {} syntax.
If you're used to Visual Basic, you might want to use the if : endif; syntax.
I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:
<?php
if ($foo) { ?>
<p>Foo!</p><?php
} else { ?>
<p>Bar!</p><?php
} // if-else ($foo) ?>
Whether that's easier to read than:
<?php
if ($foo): ?>
<p>Foo!</p><?php
else: ?>
<p>Bar!</p><?php
endif; ?>
is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)
I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.
Both are the same.
But:
If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic.
Of course it is not mandatory and you can use what ever syntax you like.
ZF uses that approach.
There is no technical difference between the two syntaxes. The alternative syntax is not new; it was supported at least as far back as PHP 4, and perhaps even earlier.
You might prefer the alternative form because it explicitly states which control structure is ending: endwhile, for example, can only terminate a while block, whereas if you encounter a brace, it could be closing anything.
You might prefer the traditional syntax, though, if you use an editor that has special support for braces in other C-like syntaxes. Vim, for example, supports several keystrokes for navigating to matching braces and to the starts and ends of brace-delimited blocks. The alternative syntax would break that editor feature.
In the end you just don't want to be looking for the following line and then having to guess where it started:
<?php } ?>
Technically and functionally they are the same.
It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.
<?php
if($something){
doThis();
}else{
echo '<h1>Title</h1>
<p>This is a paragraph</p>
<p>and another paragraph</p>';
}
?>
I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:
<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
<?php $_modes = $this->getModes(); ?>
<?php if($_modes && count($_modes)>1): ?>
<label><?php echo $this->__('View as') ?>:</label>
<?php foreach ($this->getModes() as $_code=>$_label): ?>
<?php if($this->isModeActive($_code)): ?>
<strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>
<?php else: ?>
<?php echo $_label ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</p>
<?php endif; ?>
I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.
Personally I prefer making it in two seperate sections but within the same PHP like:
<?php
if (question1) { $variable_1 = somehtml; }
else { $variable_1 = someotherhtml; }
if (question2) {
$variable_2 = somehtml2;
}
else {
$variable_2 = someotherhtml2;
}
etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;
?>
But maybe it is slower?
I think it's a matter of preference. I personally use:
if($something){
$execute_something;
}
I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.
Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)
Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.
I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.
If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing
if(/*condition*/){
/*body*/
}
compared to
if(/*condition*/):
/*body*/
endif;
This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.
I'm having one of those moments where I know I'm so close, and probably missing something super minor that's causing this to not work.
I'm using a pre-built theme, with an if statement for including or not including a link. What I want to do it put an if statement inside of THAT differentiating between internal and external links, opening external links in a new tab.
This is the portion I'm specifically working on
if(!empty($parallax_one_service_box->title)){
if( !empty($parallax_one_service_box->link) ){
if($parallax_one_service_box->link_type == 'External'){
echo '<h3 class="colored-text">'.esc_attr($parallax_one_service_box->title).'</h3>';
}else {
echo '<h3 class="colored-text">'.esc_attr($parallax_one_service_box->title).'</h3>';
}
}
else {
if (function_exists ( 'icl_translate' ) && !empty($parallax_one_service_box->id)){
echo '<h3 class="colored-text">'.icl_translate('Featured Area',$parallax_one_service_box->id.'_services_title',esc_attr($parallax_one_service_box->title)).'</h3>';
} else {
echo '<h3 class="colored-text">'.esc_attr($parallax_one_service_box->title).'</h3>';
}
}
}
So it's something along the lines of "if not empty, if external link open in a new tab." I ran it through php code checker, and the code is correct...not missing any brackets or anything. The problem seems to be that it's either opening all in a new tab or opening none in a new tab...it's not differentiating between external and internal. So I'm guessing something is wrong with the "if external" line...
Here's a link to Pastebin with the whole section of code: http://pastebin.com/kmuGiVJv
This may be a simple one for you PHP experts out there. I need to give a certain <h1> to a post else show the page/post title.
I have this so far, it works if it is on a single post page, but when I am on a different page it just shows 'the_title' instead of the page title. I think its basically about calling a php function inside an already open php tag, if that makes sense. Here is the code:
<?php
if ( is_single() ) {
echo 'News';
} else {
echo the_title();
}
?>
The Wordpress tag for the page title is <?php the_title ?>
You are echoing 'the_title' as a string, you need to actually execute the function like so:
if ( is_single() ) {
echo '<h1>News</h1>';
} else {
echo '<h1>' . the_title() . '</h1>';
}
Note the closing quote to halt the string, and the . to concatenate the WordPress function the_title(), and then another to join the ending <h1> tag.
A cleaner way is to add the tags inside the function itself, like this:
<?php the_title('<h1>', '</h1>'); ?>
No need for 'echo'.