首页 > 解决方案 > 如何将默认的 php 代码重写为有效的回显行输出?

问题描述

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

这是我们正在谈论的行:

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

标签: phpwordpress-themingecho

解决方案


让我们看看这对我们有什么帮助,因为我已经清理了一些代码。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' );

推荐阅读