Remove new lines after echoing HTML from PHP - php

I have a Wordpress function that checks if a user has filled in some fields on his or her profile. If it is filled in, echo its contents, if not: don't. Here is a stripped down version of the fun
<ul>
<?php if (get_the_author_meta('url',$theID)) : ?>
<li class="url">
Website
</li>
<?php endif; // End check for url ?>
<?php if ( get_the_author_meta('twitter',$theID)) : ?>
<li class="twitter">
Twitter
</li>
<?php endif; // End check for twitter ?>
<?php if ( get_the_author_meta('instagram',$theID)) : ?>
<li class="instagram">
Instagram
</li>
<?php endif; // End check for instagram ?>
<?php if ( get_the_author_meta('linkedin',$theID)) : ?>
<li class="linkedin">
LinkedIn
</li>
<?php endif; // End check for linkedin ?>
</ul>
This works well. However, for layout purposes I am using inline on these elements and I can't use floats. As you may know, this causes "gaps" in between the elements because they are all echoed on new lines.
I don't want these gaps. I know I can solve it by an arbitrary negative margin, but I don't want to use it because I am using a responsive, percentage based layout. The solution would be to "fill the gaps" in HTML by glueing all HTML together without new lines. As an example:
Will create gaps when displayed inline:
<ul>
<li>Twitter</li>
<li>Instagram</li>
<li>LinkedIn</li>
</ul>
Won't have gaps:
<ul>
<li>Twitter</li><li>Instagram</li><li>LinkedIn</li>
</ul>
I am looking for a PHP solution (no CSS) that can get rid of all the new lines inside the ul, but I don't know where to start. Or, more precisely, I don't know where to put the function that removes the new lines. How can I wrap all that HTML, and then replace the new lines by ... nothing?

Have you tried something like:
$string = str_replace("\n", "", $string);
or:
$string = str_replace("\n\r", "", $string);
(where $string is the html you want to get on one line)

<ul class="author-meta">
<?php
if (get_the_author_meta('url', $theID)) {
$output = '<li class="url">Website</li>';
}
if ( get_the_author_meta('twitter', $theID)) {
$output .= '<li class="twitter">Twitter</li>';
}
if ( get_the_author_meta('instagram', $theID)) {
$output .= '<li class="instagram">Instagram</li>';
}
if ( get_the_author_meta('linkedin', $theID)) {
$output .= '<li class="linkedin">LinkedIn</li>';
}
echo $output;
?>
</ul>
Edit by Bram Vanroy: make sure to use get_the_author_meta instead of the_author_meta when using the function in PHP.

You can do something like this:
ob_start();
//echo whatever stuff you need
echo str_replace(PHP_EOL, NULL, ob_get_clean());
Using PHP_EOL instead of \n or \r\n will catch line breaks regardless of platform.

You can use buffer for that :
<?php
function remove_white_spaces($buffer){
return trim(preg_replace('/\s\s+/', ' ', $buffer));
}
ob_start('remove_white_spaces');
?>
<ul>
<?php if (get_the_author_meta('url',$theID)) : ?>
<li class="url">
Website
</li>
<?php endif; // End check for url ?>
<?php if ( get_the_author_meta('twitter',$theID)) : ?>
<li class="twitter">
Twitter
</li>
<?php endif; // End check for twitter ?>
<?php if ( get_the_author_meta('instagram',$theID)) : ?>
<li class="instagram">
Instagram
</li>
<?php endif; // End check for instagram ?>
<?php if ( get_the_author_meta('linkedin',$theID)) : ?>
<li class="linkedin">
LinkedIn
</li>
<?php endif; // End check for linkedin ?>
</ul>
<?php ob_end_flush(); ?>
Catch all the output on a buffer, run a function to replace new lines with blanks, and release the buffer.

Just set your ul font-size to 0 and apply the size to your li
font-size: 15px; display: inline-block;

As per comment by #APAD1 and feedback by #CBRoe, I decided to go with the comment method. It works flawlessly, though the HTML output isn't pretty (empty comments, byebye semantics).
<ul class="author-meta">
<?php if (get_the_author_meta('url',$theID)) : ?><li class="url">
Website
</li><?php endif; // End check for url ?><!--
--><?php if ( get_the_author_meta('twitter',$theID)) : ?><li class="twitter">
Twitter
</li><?php endif; // End check for twitter ?><!--
--><?php if ( get_the_author_meta('instagram',$theID)) : ?><li class="instagram">
Instagram
</li><?php endif; // End check for instagram ?><!--
--><?php if ( get_the_author_meta('linkedin',$theID)) : ?><li class="linkedin">
LinkedIn
</li><?php endif; // End check for linkedin ?>
</ul>
Note that the comments should be outside the if clauses, because if they are inside they might not be echoed corretly, e.g. missing a opening or closing tag.

Here you go:
<ul><?php
$output = '';
if (get_the_author_meta('url', $theID)) {
$output .= '<li class="url">Website</li>';
} elseif (get_the_author_meta('twitter', $theID)) {
$output .= '<li class="twitter">Twitter</li>';
} elseif (get_the_author_meta('instagram', $theID)) {
$output .= '<li class="instagram">Instagram</li>';
} elseif (get_the_author_meta('linkedin',$theID)) {
$output .= '<li class="linkedin">LinkedIn</li>';
}
echo $output;
?></ul>

To make an easy to use version, you can store all your websites data in an array:
$site=Array(
"url"=>"Website",
"twitter"=> "Twitter",
"instagram"=> "Instagram",
"linkedin"=>"LinkedIn"
);
And then generating the whole list. I used a simple sample case where all domains are .com. You will have to improve the array format if you want more information to be stored.
<ul><?php
foreach($site as $k=>$v)
if (get_the_author_meta($k,$theID))
echo '<li class="'.$k.'"><a href="'
.(($k=="url")?"":"http://$k.com/")
.the_author_meta($k,$theID).'">'.$v.'</a></li>';
?></ul>
Don't forget to remove your empty title attribute in your a tags.
Note that there are others CSS alternatives: using display:table on your ul and display:table-cell on your li, or using display: flex and so on.

Related

Display MySQL request in PHP

I am trying to make a basic todolist but i want to display a list with task undone at the top and the done at the bottom.
Every time i try i have a blank page
<h1 class="header">To do.</h1>
<?php if (!empty($items)): ?>
<ul class="items">
<?php foreach ($items as $item): ?>
<?php if ( $item['done'] == 0 ) {
echo '<li>';
echo '<span class=\"item'?><?php echo $item['done'] ? ' done' : '' ?>"> <?php echo $item['name']; c</span>
<?php if (!$item['done']): ?>
Mark as done
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p> No tasks</p>
I have a table items with a field Done (0,1)
I have tryed to put if condition in the foreach but it failed.
Thanks for the help
At the end of your line which begins with echo '<span class=\"item'?> you set a PHP open tag but without closing it and then open another one on the next line:
<?php echo $item['name']; c</span>
<?php if (!$item['done']): ?>
It looks like you meant to close the PHP tag on the previous line with ?>.
As a side suggestion, if you use a good editor or IDE it will show you errors on front of you as you type, saves a lot of time.
Viewing your PHP error logs is a must as a developer, as it tells you of problems as you work, and this would have shown a fatal error and the line number etc.
A white page is also a sign that you have a fatal error as PHP crashes before it will output any content to the screen.
When i remove the if
The code is working
<?php if (!empty($items)): ?>
<ul class="items">
<?php foreach ($items as $item): ?>
<li>
<span class="item<?php echo $item['done'] ? ' done' : '' ?>"> <?php echo $item['name']; ?> </span>
<?php if (!$item['done']): ?>
Mark as done
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p> You have no task</p>

Links in repeater

I am using ACF on WordPress.
I have made a repeater field. Every fields work fine, except links.
The code below shows the name of URL, but the name has no link!
<?php if( have_rows('dl_box') ): ?>
<ul>
<?php while( have_rows('dl_box') ): the_row();
// vars
$content = get_sub_field('dl_link_name');
$link = get_sub_field('dl_url');
?>
<li>
<span class="link">
<?php if( $link ): ?>
<a href="<?php echo $url; ?>">
<?php endif; ?>
<?php if( $link ): ?>
</a>
<?php endif; ?>
<?php echo $content; ?>
</span>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
I think it because of this line
<a href="<?php echo $url; ?>">
but I do not know how to fix it.
Modify the markup as follows. You are attempting to access variables that haven't been declared, and the logic is out of sequence:
<li>
<span class="link">
<?php
// $link is the URL (from "dl_url")
// If there is a URL, output an opening <a> tag
if( $link ) {
echo '<a href="' . $link . '">';
}
// $content is the name (from "dl_link_name")
// always output the name
echo $content;
// If there is a URL, need to output the matching closing <a> tag
if( $link ) {
echo '</a>';
}
</span>
</li>
Note:
I have learned to dislike markup / logic like that - it doesn't make a lot of sense. I'd rather do something like this - it's simpler, easier to read, and more compact:
<li>
<span class="link">
<?php
// if there is a url, output the ENTIRE link
if ( $link ) {
echo '' . $content . '';
// otherwise just output the name
} else {
echo $content;
} ?>
</span>
</li>

Echo a string with no spaces using PHP

I have a foreach loop with list of links, and I'm trying to remove the spaces in the strings because I'll be using it as an href. So far, I successfully removed the spaces, but the code I wrote made a wide space before the string. Here's my foreach loop
<ul class="list grid effect-6" id="grid">
<?php foreach ($ppmtenants as $ppmtenant): ?>
<li><span class="tenant"><?php echo $ppmtenant['label'] ?><a href="<?php echo $this->getURL() ?>?___store=
<?php
$ppmtenantnospace = preg_replace('/\s+/','',$ppmtenant['label']);
echo strtolower($ppmtenantnospace);
?>"></a></span></li>
<?php endforeach; ?>
</ul>
And below is what I did to remove the spaces. I used preg_replace. Now, the spaces are gone, but it has a wide space before the string.
<?php
$ppmtenantnospace = preg_replace('/\s+/','',$ppmtenant['label']);
echo strtolower($ppmtenantnospace);
?>
Live example here: http://powerplantv2.jehzlau.net/brands.
Screenshot here: http://i.imgur.com/wpQwxso.png
As you can see, if you hover on the images, there's an unwanted space after the ?. There should be no space so that my permalinks will work. If that space disappears, my problem will be solved. But I don't know how to make it disappear. I hope a php expert here can help me. :(
The problem is comming from the spaces in your html. To fix, simply move the variable declaration of $ppmtenantnospace above the li output, then echo it in at the correct place:
<ul class="list grid effect-6" id="grid">
<?php foreach ($ppmtenants as $ppmtenant):
$ppmtenantnospace = preg_replace('/\s+/','',$ppmtenant['label']);?>
<li><span class="tenant"><?php echo $ppmtenant['label'] ?></span></li>
<?php endforeach; ?>
</ul>
The whitespace is actually in your HTML code
You should open the php tag right after =
<ul class="list grid effect-6" id="grid">
<?php foreach ($ppmtenants as $ppmtenant): ?>
<li><span class="tenant"><?php echo $ppmtenant['label'] ?><a href="<?php echo $this->getURL() ?>?___store=<?php
$ppmtenantnospace = preg_replace('/\s+/','',$ppmtenant['label']);
echo strtolower($ppmtenantnospace);
?>"></a></span></li>
<?php endforeach; ?>
</ul>
Try opening the PHP tag before the newline in your Code
<ul class="list grid effect-6" id="grid">
<?php foreach ($ppmtenants as $ppmtenant): ?>
<li><span class="tenant"><?php echo $ppmtenant['label'] ?><a href="<?php echo $this->getURL() ?>?___store=<?php
$ppmtenantnospace = preg_replace('/\s+/','',$ppmtenant['label']);
echo strtolower($ppmtenantnospace);
?>"></a></span></li>
<?php endforeach; ?>
</ul>
have you tried to stick your <?php to your ?___store=? because the 4 spaces before the <?php are not ignored since they are not PHP code but HTML output
$spaceless_string = strtr($stringwithspaces, array(' ' => ''));

styling php twitter feed

I'm not quite sure how to go about styling this particular bit of php:
<div id="twitter-feed">
<span style="font-weight:bold;">#frshstudio</span>
<?php
include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=frshstudio');
$maxitems = $rss->get_item_quantity(3);
$rss_items = $rss->get_items(0, $maxitems);
?>
<ul>
<?php if ($maxitems == 0) echo '<li>No items.</li>';
else
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<li>
<a href='<?php echo $item->get_permalink(); ?>'>
<?php echo $item->get_title(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div><!-- end twitter-feed -->
Ideally, I'd like to replace the 'FRSHStudio' before each tweet with a bullet point. Also, maybe some padding between each tweet so the feed isn't as cluttered.
Live site.
Any and all help is greatly appreciated.
To remove the FRSHStudio in each item, you could use this code :
<?php echo str_replace('FRSHStudio: ', '', $item->get_title()); ?>
Then, in css, to add bullets and some padding on each item of the list, use this :
#twitter-feed ul li {
list-style: disc;
padding-bottom: 4px;
padding-left: 10px
}

PHP - limiting the output of a plugin

I'm using a plugin titled "WP Recent Links" which I first learned about via Eric Meyer's site. Eric uses to display a Link Log within his site and I'm doing the same on my test site - http://matala.jorgeledesma.net/ but I'm running into a little situation and that is that I don't know how to limit the output either on the sidebar or the actual page - http://matala.jorgeledesma.net/recent-links/
My goal is to have it echo only the first 5 entries on the sidebar and for the recent-links page only echo the current month. The code below displays the sidebar properly
<?php if (!is_page('48')) { ?>
<aside id="meta" class="widget">
<h1 class="widget-title">Link Log</h1>
<?php if ($links = rp_recentlinks_home()) { ?>
<ul>
<?php foreach ($links as $link) { ?>
<b><li><?php echo wptexturize($link->link_text); ?></b>
<?php if ('' != $link->link_caption) { ?>→
<?php echo wptexturize(convert_smilies($link->link_caption)); ?><?php } ?>
</li>
<?php } ?>
</ul>
<?php } ?>
</aside>
<?php } ?>
and this code display the actual recent-links page
<h1 class="page-title"><?php rp_recentlinks_archive_header(); ?></h1>
</header>
<div class="entry-content">
<?php $links = rp_recentlinks_archive_page(); ?>
</div>
<?php if ($links) { ?>
<ul>
<?php foreach ($links as $link) { ?>
<p id="rlink-<?php echo $link->ID; ?>"><?php echo wptexturize($link->link_text); ?>
<?php if ('' != $link->link_caption) { ?>→
<?php echo wptexturize(convert_smilies($link->link_caption)); ?><?php } ?>
</p>
<?php } ?>
</ul>
<?php } ?>
I tried putting the following code in the body.
$list = array_slice($input, 0, 5); // $list now only having first 5 item.
But I don't know how to apply it, if that's the command at all. So perhaps, someone can guide in the right direction. Thanks in advance, Jorge.
Looks like all you have to add is this before you pass $links to the foreach loop:
$links = array_slice($links,0,5);

Categories