How do I execute php code within a variable containing html - php

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');

Related

Put values of a foreach loop inside a div

<?php
$recent_posts = wp_get_recent_posts(array('post_type'=>'projet'));
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
if ( has_post_thumbnail( $recent["ID"]) ) {
echo get_the_post_thumbnail($recent["ID"],'thumbnail');
}
if (has_excerpt($recent["ID"]) ){
// echo get_the_excerpt($recent["ID"],'the_excerpt');
echo '<p class="excerpt">' . get_the_excerpt($recent["ID"],'the_excerpt') . '</p>';
}
}
?>
Hi, I would like to know how to put all my foreach loop inside a div ? I want each $recent_posts to be inside a div, right now they're one after the other. (btw it's my first post here, excuse me if i'm not clear)
##EDIT##
Here's my html :
<h2>Maquette UX/UI</h2> <img width="150" height="150" src="http://localhost/wordpress/wp-content/uploads/2021/04/vignette_maquette-150x150.jpg" class="attachment-thumbnail size-thumbnail wp-post-image"
alt="" loading="lazy" />
<p class="excerpt">Projet 1</p>
<h2>Intégration Baniera</h2> <img width="150" height="150" src="http://localhost/wordpress/wp-content/uploads/2021/04/vignette_baniera_homepage-150x150.jpg" class="attachment-thumbnail size-thumbnail wp-post-image"
alt="" loading="lazy" />
<p class="excerpt">Projet 2</p>
<h2>Intégration PHP</h2> <img width="150" height="150" src="http://localhost/wordpress/wp-content/uploads/2021/04/order_homepage-150x150.jpg" class="attachment-thumbnail size-thumbnail wp-post-image"
alt="" loading="lazy" />
<p class="excerpt">Projet 3</p>
<p class="excerpt"></p>
</div>
And I want every "group" to be inside a div, right now they're all together
Ok it works now, I wrapped the content of foreach like so :
<?php
$recent_posts = wp_get_recent_posts(array('post_type'=>'projet'));
foreach( $recent_posts as $recent ){
echo '<div class="foreach_wrapper">';
echo '<h2><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a></h2> ';
if ( has_post_thumbnail( $recent["ID"]) ) {
echo get_the_post_thumbnail($recent["ID"],'thumbnail');
}
if (has_excerpt($recent["ID"]) ){
// echo get_the_excerpt($recent["ID"],'the_excerpt');
echo '<p class="excerpt">' . get_the_excerpt($recent["ID"],'the_excerpt') . '</p>';
}
echo '</div>';
}
?>
You can echo a div around the foreach, a little side note, you are using a <li> element but forgot the <ul> wrapper please validate your HTML with a HTML validator.
<?php
echo '<div>'; /* I added this */
$recent_posts = wp_get_recent_posts(array('post_type'=>'projet'));
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
if ( has_post_thumbnail( $recent["ID"]) ) {
echo get_the_post_thumbnail($recent["ID"],'thumbnail');
}
if (has_excerpt($recent["ID"]) ){
// echo get_the_excerpt($recent["ID"],'the_excerpt');
echo '<p class="excerpt">' . get_the_excerpt($recent["ID"],'the_excerpt') . '</p>';
}
}
echo '</div>'; /* I added this */
?>

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' );

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

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' );

Php code between Tab Shortcode

I want to insert php code in between tabby tabs shortcodes.
I am using a plugin tabby tab for tab view and have added this code in my theme template:
<?php echo do_shortcode('[tabby title="Gallary Name"]
name content
[tabby title="Images"]
[tabbyending]'); ?>
I want to use a custom fields gallery under images tab using code like this:
<?php echo do_shortcode('[tabby title="Gallary Name"]
name content
[tabby title="Images"]
<?php
$i = 0;
$images = get_field('vil_pics');
if( $images ): ?>
<div>
<ul>
<?php foreach( $images as $image ): ?>
<li<?php if ( $i % 3 == 0 ) echo ' class="break"' ?>>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
</a><p>.</p>
</li>
<?php endforeach; ?>
</ul></div>
<?php endif; ?>
[tabbyending]'); ?>
This code is not working, it's showing a blank page. How can I fix this?
Tabby uses a global variable to track what's going on, so I think either one of these will work. The first one is a little more straightforward, but the second one will definitely work.
Option 1: output everything in order:
echo do_shortcode( '[tabby title="Gallery Name"] name content' );
echo do_shortcode( '[tabby title="Images"]' );
// your php code as-is
$i = 0;
$images = get_field('vil_pics');
if( $images ): ?>
<div>
<ul>
<?php foreach( $images as $image ):
$i++ ?>
<li<?php if ( $i % 3 == 0 ) echo ' class="break"' ?>>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['thumbnail']; ?>" alt="<?php echo $image['alt']; ?>" />
</a><p>.</p>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif;
echo do_shortcode( '[tabbyending]' );
or Option 2: save everything to a variable and output it all at once:
$output = '';
$output .= '[tabby title="Gallery Name"] name content';
$output .= '[tabby title="Images"]';
$i = 0;
$images = get_field('vil_pics');
if ( $images ) {
$output .= '<div><ul>';
foreach( $images as $image ) {
$i++;
$li_class = ( $i % 3 == 0 ) ? ' class="break"' : '';
$output .= '<li' . $li_class . '>';
$output .= '<a href="' . $image['url'] . '">';
$output .= '<img src="' . $image['sizes']['thumbnail'] . '" alt="' . $image['alt'] . '" />';
$output .= '</a><p>.</p></li>';
}
$output .= '</div></ul>';
}
$output .= '[tabbyending]';
echo do_shortcode( $output );
Note that I didn't see anything increasing $i so I added that. Everything else is as-is.

How can i get first image if the post has no post thumbnail in wordpress

I have created the sidebar widget for popular, recent and most commented posts in my theme. I have some posts which don't contain the image thumbnail.
This is the popular query posts for 5 posts in my widget
<?php if (!empty($popular_posts)) { ?>
<div class="tab-pane fade in active" id="popular">
<div class="row">
<!-- ********************************************** -->
<!-- Popular Posts Tab -->
<!-- ********************************************** -->
<?php
$YPE_options = get_option( 'YPE_sidebar_option_name' );
$popular = new WP_Query( array(
'posts_per_page' => $popular_limit,
'meta_key' => 'post_views_count', // this is function within functions.php for counting post veiews
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
while ( $popular->have_posts() ) : $popular->the_post();
$html = '<article>';
$html .= '<section class="bootstrap-nav-thumb">';
$html .= '<p>';
$html .= '<a href="' . get_permalink() . '">';
$html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive '.$YPE_options['YPE_sidebar_PRC_thumb_style'].''));
$html .= '</a>';
$html .= '</p>';
$html .= '</section>';
$html .= '<aside class="bootstrap-title-info">';
$html .= '<p>';
$html .= ''.get_the_title().'';
$html .= '</p>';
$html .= '<p class="text-muted">' . get_the_date() . '||'. getPostViews(get_the_ID()) . '</p>';
$html .= '</aside>';
$html .= '</article>';
echo $html;
endwhile;
?>
</div> <!-- End row of popular posts -->
</div> <!-- End tab-pane of popular posts -->
<?php } ?>
how can i add conditional statement to this code
$html .= '<a href="' . get_permalink() . '">';
$html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive '.$YPE_options['YPE_sidebar_PRC_thumb_style'].''));
$html .= '</a>';
Note: i want to say if has post thumbnail put the posts thumbnail and if not has the thumbnail put the first image instead of the post thumbnail
$thumb = get_the_post_thumbnail(get_the_ID());
if(!empty($thumb))
$image = $thumb;
else {
$image = '<img src="';
$image .= catch_that_image();
$image .= '" alt="" />'; }
And put your function as
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Something like this could work:
$html .= '<a href="' . get_permalink() . '">';
if ( has_post_thumbnail() ) {
$html .= get_the_post_thumbnail(get_the_ID(), array('class' => 'img-responsive '.$YPE_options['YPE_sidebar_PRC_thumb_style'].''));
} else {
$html .= "<img src='". echo wp_get_attachment_image_src(0,'thumbnail') .'" class="img-responsive ' .$YPE_options['YPE_sidebar_PRC_thumb_style'].' " />';
};
html .= '</a>';

Categories