如何将默认 php 代码重写为有效的回显行输出?

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

我是 PHP 的新手,为了开发 Wordpress 主题,我需要重写以下 php/html 代码行,以便我可以在我的 functions.php. 我发现我需要将其重写为“回声”调用,但我总是收到错误消息,因为我的语法错误。

这是我们正在谈论的行:

<div <?php post_class( 'brick_item ' . $termString ) ?> onclick="location.href='<?php the_permalink(); ?>'">

我试过几次了,例如

echo '<div class="'. post_class("brick_item" . $termString); .'" onclick=location.href="'. the_permalink() .'">';

但是我在封装我猜的东西时做错了。

编辑: 根据要求, 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' );

让我们看看这对我们有何帮助,因为我已经稍微清理了代码。 div 会在那里闲逛,所以我把永久链接放在里面。

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

你的行中间有一个分号

echo '<div class="'. post_class("brick_item" . $termString); .'" onclick=location.href="'. the_permalink() .'">';

应该是

echo '<div class="'. post_class("brick_item" . $termString) .'" onclick=location.href="'. the_permalink() .'">';

分号表示 php 中的行尾,因此您的代码首先执行

echo '<div class="'. post_class("brick_item" . $termString);

很好,但只有您想要的一半。 然后 php 尝试执行

.'" onclick=location.href="'. the_permalink() .'">';

但不知道如何处理行首的点。点的意思是append string before to string after,但是之前没有任何东西,所以这是一个编译错误。 您也可以在第二行添加另一个 echo 而不是点

echo '" onclick=location.href="'. the_permalink() .'">';