2021年5月1日星期六

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.

https://stackoverflow.com/questions/67351869/how-do-i-execute-php-code-within-a-variable-containing-html May 02, 2021 at 07:58AM

没有评论:

发表评论