How to rewrite default php code to a valid echo line output? - php

I am new to PHP and for the development of a Wordpress theme I need to re-write the following line of php/html code so that I can use it in my functions.php.
I found out that I would need to rewrite it as an "echo" call, but I am always getting an error because my syntax is wrong.
This is the line we're talking about:
<div <?php post_class( 'brick_item ' . $termString ) ?> onclick="location.href='<?php the_permalink(); ?>'">
I've tried several times, e.g.
echo '<div class="'. post_class("brick_item" . $termString); .'" onclick=location.href="'. the_permalink() .'">';
but I am doing something wrong in encapsulating things I guess.
EDIT:
As requested, the part of the functions.php
function get_latest_posts() {
echo '<div class="latest-posts">';
echo '<div class="brick_list">';
$args = array(
post_type => 'post',
cat => '-3,-10',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if ( $latestposts_query->have_posts() ) : while ( $latestposts_query->have_posts() ) : $latestposts_query->the_post();
echo '<div '. post_class( $termString ) .' onclick=location.href='. the_permalink() .'>';
endwhile; else :
get_template_part('template_parts/content','error');
endif;
wp_reset_postdata();
echo '</div>';
echo '</div>';
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );

There is a semicolon in the middle of your line
echo '<div class="'. post_class("brick_item" . $termString); .'" onclick=location.href="'. the_permalink() .'">';
should be
echo '<div class="'. post_class("brick_item" . $termString) .'" onclick=location.href="'. the_permalink() .'">';
semicolons signify end of line in php, thus your code did first execute
echo '<div class="'. post_class("brick_item" . $termString);
which is fine, but only half of what you want.
Then php tries executing
.'" onclick=location.href="'. the_permalink() .'">';
but doesn't know what to do with a dot at the start of the line. Dot means append string before to string after, but there is nothing before, so it's a compile error.
You can also just add another echo to the second line instead of the dot
echo '" onclick=location.href="'. the_permalink() .'">';

Let's see where this gets us as I've cleaned up the code a bit. The div would just be hanging out there so I put the permalink in it.
function get_latest_posts() {
echo '<div class="latest-posts">';
echo '<div class="brick_list">';
$args = array(
post_type => 'post',
cat => '-3,-10',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if($latestposts_query->have_posts()) {
while($latestposts_query->have_posts()) {
$thePost = $latestposts_query->the_post();
echo '<div ' . post_class($thePost) . ' onclick="location.href=\'' . the_permalink() . '\'">' . the_permalink() . '</div>';
}
} else {
get_template_part('template_parts/content','error');
}
wp_reset_postdata();
echo '</div>';
echo '</div>';
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );

Related

How to fix Warning: Use of undefined constant active - assumed 'active' (this will throw an Error in a future version of PHP)

I'm currently working on a WirdPress Theme project using Bootstrap v5.0.2 and PHP 7.3.28.
I'm tryng to insert the Bootstrap Carousel Component in a custom widget but when I debug the code I recive this "Warning: Use of undefined constant active - assumed 'active' (this will throw an Error in a future version of PHP) in ... on line 70"
This is the line that give me the error:
echo ' class="';if ( $the_query->current_post == 0 ) : active ;endif; '"> ';
I try to change active in $active or 'active' but it doen't works.
Because I'm a newbie in PHP I don't understand what I'm doing wrong.
I hope someone can help me to solve this problem.
Thanks
This is the whole code:
<?php
// Register and load the widget
function tabulas_slider_widget() {
register_widget( 'Tabulas_Slider_Widget' );
}
add_action( 'widgets_init', 'tabulas_slider_widget' );
// Creating the widget
class Tabulas_Slider_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
public function __construct() {
parent::__construct(
// Base ID of widget
'Tabulas_Slider_Widget',
// Widget name will appear in UI
esc_html__('Last Post Slider', 'tabulas'),
// Widget description
array( 'description' => esc_html__( 'Display the 3 last post published with featured image in the form of a Slider', 'tabulas'), )
);
}
/**
* Front-end display of widget.
*
* #see WP_Widget::widget()
*
* #param array $args Widget arguments.
* #param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
// WP_Query arguments
$args = array(
'post_type' => 'post',
'posts_per_page' => 3,
);
// The Query
$the_query = new WP_Query ( $args );
echo ' <div id="carouselExampleCaptions" ';
echo ' class="carousel slide" ';
echo ' data-bs-ride="carousel" ';
echo ' data-bs-interval="10000"> ';
echo ' <div class="carousel-indicators"> ';
if ( $the_query->have_posts() ) :
echo $args['before_widget'];
if ( $title ){
echo $args['before_title'] . $title . $args['after_title'];
}
echo ' <ol class="carousel-indicators"> ';
while ( $the_query->have_posts() ) : $the_query->the_post();
echo ' <li data-target="#ExampleCarouselID" ';
echo ' data-slide-to="';$the_query->current_post;'" ';
echo ' class="';if ( $the_query->current_post == 0 ) : active ;endif; '"> ';
echo ' </li> ';
endwhile;
echo ' </ol> ';
rewind_posts();
echo ' <button type="button" ';
echo ' data-bs-target="#carouselExampleCaptions" ';
echo ' data-bs-slide-to="0" ';
echo ' class="active" ';
echo ' aria-current="true" ';
echo ' aria-label="Slide 1">';
echo ' </button> ';
echo '<button type="button" ';
echo ' data-bs-target="#carouselExampleCaptions" ';
echo ' data-bs-slide-to="1" ';
echo ' aria-label="Slide 2">';
echo ' </button> ';
echo '<button type="button" ';
echo ' data-bs-target="#carouselExampleCaptions" ';
echo ' data-bs-slide-to="2" ';
echo ' aria-label="Slide 3">';
echo '</button>';
echo '</div>';
echo ' <div class="carousel-inner"> ';
while ( $the_query->have_posts() ) : $the_query->the_post();
$thumbnail_id = get_post_thumbnail_id();
$thumbnail_url = wp_get_attachment_image_src( $thumbnail_id, 'full', true );
$thumbnail_meta = get_post_meta( $thumbnail_id, '_wp_attatchment_image_alt', true );
echo ' <div class="carousel-item ';
if ( $the_query->current_post == 0 ) : active ;endif; '"> ';
if ( has_post_thumbnail() ) {
echo '<a href="';the_permalink(); echo '">';
the_post_thumbnail('full');
echo '</a>';
}
echo '<div class="carousel-caption d-none d-md-block">';
echo '<h5>';
the_title();
echo '</h5>';
echo '</div>';
echo '</div>';
endwhile;
wp_reset_query();
echo '</div>';
echo '<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">';
echo '<span class="carousel-control-prev-icon" aria-hidden="true">';
echo '</span>';
echo' <span class="visually-hidden">';esc_html_e( 'Previous', 'tabulas' );
echo '</span>';
echo '</button>';
echo '<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">';
echo '<span class="carousel-control-next-icon" aria-hidden="true">';
echo '</span>';
echo '<span class="visually-hidden">';esc_html_e( 'Next', 'tabulas' );
echo '</span>';
echo '</button>';
echo '</div>';
echo $args['after_widget'];
wp_reset_postdata();
endif;
}
You must echo 'active' and end of line:
echo ' class="';if ( $the_query->current_post == 0 ) : echo 'active' ;endif; echo '"> ';

How do I execute php code within a variable containing html

I assembled a Wordpress shortcode but it throws an error in the block editor: "Updating failed. The response is not a valid JSON response." Notwithstanding, the edits are saved. I've been told the reason I get the error is my "shortcode handler function is generating output. Such functions must collect all output into a variable which is returned."
Below are (1) the code that works but causes the error message and (2) my pseudo code to fix the problem by assigning the 'a href' to a variable $html, but doesn't.
(1)
function make_header() {
$args = array(
'posts_per_page' => 1,
'category_name' => 'headlines',
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
?>
<a href="<?php the_permalink() ?>">
<div><img src="<?php echo $featured_img_url; ?>" width="100%" /></div>
<h2>
<?php the_title(); ?>
</h2></a>
<?php
}
wp_reset_postdata();
}
}
add_shortcode('make_header', 'make_header');
(2)
$html = '
<a href="<?php the_permalink() ?>">
<div><img src="<?php echo $featured_img_url; ?>" width="100%" /></div>
<h2>
<?php
the_title(); ?> </h2></a>';
}
wp_reset_postdata();
return $html;
Thanks for your help.
Try below code
$html = ' <div><img src="'. echo $featured_img_url .'" width="100%" /></div> <h2>'. the_title().' </h2>';
the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments. 
You could to use concatenation like so:
$html = '<a href="' . esc_url(get_the_permalink()) . '">';
$html .= '<div>';
$html .= '<img src="' . $featured_img_url . '" width="100%" />';
$html .= '</div>';
$html .= '<h2>' . get_the_title() . '</h2></a>';
Also, use get_the_permalink() and get_the_title() as these functions are returning their result instead of outputting it.
The full code would then look something like this:
function make_header() {
$html = '';
$args = array(
'posts_per_page' => 1,
'category_name' => 'headlines',
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
$featured_img_url = esc_url(get_the_post_thumbnail_url(get_the_ID(),'full'));
$html = '<a href="' . esc_url(get_the_permalink()) . '">';
$html .= '<div>';
$html .= '<img src="' . $featured_img_url . '" width="100%" />';
$html .= '</div>';
$html .= '<h2>' . get_the_title() . '</h2></a>';
}
wp_reset_postdata();
}
return $html;
}
add_shortcode('make_header', 'make_header');

How to rewrite an echo function to a return value for a Wordpress theme

I am new to PHP and I am glad that I have written the following function (which works as it should) on my own so far:
function get_latest_posts() {
echo '<div class="latest-posts">';
echo '<div class="brick_list">';
$args = array(
post_type => 'post',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if ( $latestposts_query->have_posts() ) : while ( $latestposts_query->have_posts() ) : $latestposts_query->the_post();
echo ' <div ';
post_class("brick_item" . $termString );
echo ' onclick="location.href=\'';
the_permalink();
echo ' \'"> ';
echo ' <div class="brick_item-image"> ';
if ( has_category( 'sample' ) ) {
echo ' <img src="/wp-content/uploads/placeholder_1.png" /> ';
} elseif ( has_post_thumbnail() ) {
the_post_thumbnail();
} else {
echo ' <img src="/wp-content/uploads/placeholder_2.png" /> ';
}
echo ' </div> ';
echo ' <div class="brick_item-header"> ';
echo ' <h4><a href=" ';
the_permalink();
echo ' "> ';
the_title();
echo ' </a></h4> ';
echo ' </div> ';
echo ' </div> ';
endwhile; else :
get_template_part('template_parts/content','error');
endif;
wp_reset_postdata();
echo '</div>';
echo '</div>';
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );
But now I definitly need your help...
As you can see I want to use this function in a shortcode. Currently it displays first on my page, and Google says, this is because I am echoing the content and I would need to give a return value.
How do I do this?? Is it just replacing the word "echo" with the word "return" ? I have no idea...
I have condensed a few statements together for readability but here's what that would look like:
function get_latest_posts() {
$return = '<div class="latest-posts"><div class="brick_list">';
$args = array(
post_type => 'post',
posts_per_page => 3
);
$latestposts_query = new WP_Query($args);
if ( $latestposts_query->have_posts() ) : while ( $latestposts_query->have_posts() ) : $latestposts_query->the_post();
$return .= ' <div ' . post_class("brick_item" . $termString ) . ' onclick="location.href=\'' . get_permalink() . '\'"> ';
$return .= '<div class="brick_item-image">';
if ( has_category( 'sample' ) ) {
$return .= '<img src="/wp-content/uploads/placeholder_1.png" />';
} elseif ( has_post_thumbnail() ) {
$return .= get_the_post_thumbnail();
} else {
$return .= '<img src="/wp-content/uploads/placeholder_2.png" />';
}
$return .= '</div> <div class="brick_item-header"> <h4>' . the_title('','',false) . '</h4></div></div>';
endwhile; else :
get_template_part('template_parts/content','error');
endif;
wp_reset_postdata();
$return .= '</div></div>';
return $return;
}
add_shortcode( 'get_latest_posts', 'get_latest_posts' );

default thumbnail for wordpress site

I'm trying to modify my custom wp theme and add related post block. I want to add default thumbnail for posts which doesn't have it. Below code is working fine but i can't archive how to add default img.
$args = array( 'numberposts' => '4','post__not_in' => array($post->ID));
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ) {
if($recent['post_status']=="publish") {
if ( has_post_thumbnail($recent["ID"])) {
echo '<div><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], 'thumbnail'). $recent["post_title"].'</a></div> ';
} else {
echo '<div><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a></div>';
}
}
}
In order to print the default thumbnail if the posts featured image is not found you have to print the default image that you have in your images folder.
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/default-thumb-img.png"
alt="<?php the_title(); ?>" />
<?php } ?>
What the above code does?
It checks whether the post has thumbnails, if not it assigns the default-thumb-img.png ( Change it to your image name) as per your requirement.
my solution is just hardcode absolute link to default thumbnail
$args = array( 'numberposts' => '4','post__not_in' => array($post->ID));
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
if($recent['post_status']=="publish") {
if ( has_post_thumbnail($recent["ID"])) {
echo '<div class="col-md-3 col-lg-3"><div class="recent-post-holder"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . get_the_post_thumbnail($recent["ID"], 'thumbnail'). $recent["post_title"].'</a></div></div> ';
} else {
echo '<div class="col-md-3 col-lg-3"><div class="recent-post-holder"><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . "<img src='/*add link here*/'>". $recent["post_title"].'</a></div></div>';
}
}
}

my php echo statement for an <a href="#"> is making the url visible

I am going by this tutorial (https://redvinestudio.com/how-to-build-isotope-portfolio-in-your-wordpress-theme/), and when I am working on the part where the portfolio items are displayed as links, the url that the link leads to is being displayed above the item. Below is the prescribed code:
echo '<div class="all portfolio-item '. $tax .'">';
echo '<a href="'. the_permalink() .'" title="'. the_title_attribute() .'">';
echo '<div class="thumbnail">'. the_post_thumbnail('thumbnail') .'</div>';
echo '<h2>'. the_title() .'</h2>';
echo '</a>';
/*echo '<div>'. the_excerpt() .'</div>';*/
echo '</div>';
You can't use the_permalink() within an echo, because it echoes data itself. Instead, you need to use get_permalink(). You also need to modify the_title_attribute() to avoid a duplicated echo there:
echo '<a href="'. get_permalink() .'" title="'. the_title_attribute( 'echo=0' ) .'">';
EDIT: You need to comb through your code to remove all instances of code that is echoing content within an echo. This includes the_title(), the_post_thumbnail(), etc.
the_permalink() will always echo the URL of the object, which means you're telling it to echo twice. Change it to get_permalink() and it should work.

Categories