首页 > 解决方案 > 在 wordpress 中单独打印的标签

问题描述

我的wordpress首页有以下代码,但是在检查html中的实际结果时,a标签没有围绕内容。经过一番检查,我发现php行回显类别有问题,但我不知道如何纠正。

        <?php
            // args query
            $args = array(
                'post_type'      => 'post',
                'posts_per_page' => 5,
                'order'          => 'DESC'
            );

            // custom query
            $recent_posts = new WP_Query($args);

            // check that we have results
            if($recent_posts->have_posts()) : ?>

            <ul class="article_list">

                <?php
                // start loop
                while ($recent_posts->have_posts() ) : $recent_posts->the_post(); ?>

                <li class="regular">
                    <a href="<?php echo get_permalink(); ?>">
                        <div class="text">
                            <p class="category"><?php echo the_category(); ?></p>
                            <h3 class="article_title"><?php echo mb_strimwidth(get_the_title(), 0, 80, '...'); ?></h3>
                            <p class="date"><?php echo get_the_date( 'Y-m-d' ); ?></p>
                        </div>
                        <div class="mask">
                            <img src="<?php the_post_thumbnail_url();?>" alt="" class="art_img">
                        </div>
                    </a>
                </li>
            <?php endwhile; ?>
        </ul>
    <?php endif;
    // reset query
    wp_reset_postdata();
    ?>

标签: phpwordpress

解决方案


WordPress 有两种类型的后变量函数。get_函数将返回一个值,以便可以对其进行操作并稍后将其打印到文档中。the_函数做同样的事情,但是它们会自动将值打印到文档中,并通过任何适用的过滤器运行它。

注意:通常它们更像是the_content()get_the_content()的同义词,但这些(imo)命名不佳。

the_category()只是一个回显的包装函数get_the_category_list()

改变:

<p class="category"><?php echo the_category(); ?></p>

至:

<p class="category"><?php echo get_the_category_list(); ?></p>

或者

<p class="category"><?php the_category(); ?></p>

这应该可以解决您的问题。现在,您正在回显一个已经回显输出的函数。

编辑:根据您的评论,我现在看到您的意思是<a>标签是自己打印的。那是因为the_category()默认get_the_category_list()输出一个链表。因此,您在现有标签有链接的类别,<a href="<?php echo get_permalink(); ?>">这是无效的 HTML。链接中不能有链接。

您要么想要运行当前函数,strip_tags()要么使用不同的类别函数,例如get_categories()并循环遍历它


推荐阅读