在导航栏中显示WordPress页面的前几个单词


Displaying first few words of WordPress page in the nav

我想显示一个WordPress导航,在它下面有每个页面的前几个单词。

这是我目前拥有的:

<?php wp_list_pages('title_li=&link_after=<span>FIRST FEW WORDS HERE</span>'); ?>

我希望输出是这样的:

<li><a href="#">Home<span>Welcome to the website</span></a></li>

如有任何帮助,不胜感激

我唯一能想到的就是这样做:

使用wp_get_pages获取所有标题(或您想要的标题),然后使用查询访问数据库,该查询将获取使用该标题的每个帖子。因此,对于get_pages返回的数组中的每个标题,您将获得相应的帖子。在SQL或PHP中使用substring方法来获取前几个单词,并显示您想要的。

这就是逻辑,我对代码有点生疏,所以我不想让你困惑。

我不认为有一种方法可以通过传递参数到wp_list_pages来将额外的文本放在锚内。但是,您可以过滤它并使用preg_replace。例如…

add_filter('wp_list_pages', function($data) {
    return preg_replace('/(<a[^>]+[^<]+)<'/a>/si', '''1<span>FIRST FEW WORDS HERE</span></a>', $data);
});

虽然我使用preg_replace(),你也可以(也许应该)使用DomDocument,但这将适用于大多数用例。

另一种方法是使用自定义walker

另一个选择是创建一个自定义循环,并将其添加到主题的"index.php"文件中,您想要显示它。

一个简短的示例:

<div id="nav"><ul>
 <!-- start the loop-->
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
 <li class="nav_post">
 <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
 <span><?php formatPreview(the_content()); ?></span></a>
 </li>
 <!-- stop the loop-->
 <?php endwhile; else: ?>
 <p>No posts!</p>
 <?php endif; ?>
</ul></div>

the_permalink()、the_title()和the_content()是这里用帖子信息填充自定义导航的关键角色。然后只需为nav ID、nav_post类和h2/p添加适当的css,就可以了!你可能会想要在一定数量的帖子后硬停止循环-我怀疑你想要在导航栏中列出每个帖子!

你必须单独创建"formatPreview()"函数来控制如何格式化每篇文章内容的预览-但它应该不难,只是substr前几个单词!