HTML5空白 将摘录保存到数组中



我正在使用HTML5Blank作为起始主题,它带有这个函数,它返回40个字符的摘录:

<?php html5wp_excerpt('html5wp_custom_post'); ?>

我的主博客页面更复杂,所以我使用数组将值存储到其中,并在我需要的地方回显它们:

<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php $post_titles[$counter] = get_the_title($post->ID); ?>
<?php $post_excerpts[$counter] = html5wp_excerpt('html5wp_custom_post', $post_id); ?>
<?php $post_permalinks[$counter] = get_the_permalink($post->ID); ?>
<?php $post_thumbs[$counter] = get_the_post_thumbnail($post->ID, '', array('class' => 'img-fluid')); ?>
<?php $counter++; ?>
<?php endwhile; ?>

所有其他字段都有效,我可以回显它们,但我不知道如何使摘录工作,因为它没有回显任何内容:

<?php echo $post_excerpts[0]; ?>

首先,我注意到您正在使用一个名为 $post_id 的变量,据我所知,该变量尚未定义。您需要添加一个 $post_id = $post->ID;之前或或者您可以使用:

<?php $post_excerpts[$counter] = html5wp_excerpt('html5wp_custom_post', $post->ID); ?>

也许这已经解决了你的问题。但为了确保这一点,我会更进一步。


我看了一下HTML5-Blank-Theme的功能.php https://github.com/html5blank/html5blank/blob/master/src/functions.php

// Create 40 Word Callback for Custom Post Excerpts, call using html5wp_excerpt('html5wp_custom_post');
function html5wp_custom_post($length)
{
return 40;
}

因此,该函数仅返回值 40。我想你可以像这样简单地使用 html5wp_excerpt((:

html5wp_excerpt(40);

也许html5wp_custom_post有问题,所以你可以摆脱它来测试一下。而且我也想,如果它只返回一个数字,为什么要使用附加函数......您可以在函数调用中轻松设置它。

我不知道这个函数是否接受帖子 ID 作为参数。所以也许它只能在单个页面内使用.php。我找不到有关此的文档,也许您可以做一些研究并找出答案。

这是实现它的另一种方法:


您可以使用接受帖子 id 的 get_the_title(( 函数。不幸的是,get_the_excerpt(( 不接受它。

因此,我们首先需要获取帖子对象,然后应用过滤器来获取帖子的摘录。通过将以下代码放在 while 循环中来执行此操作:

<?php $current_post = get_post($post->ID); ?>

您现在将当前帖子作为对象。在下一行中,我们应用过滤器并将结果保存到数组的右侧索引位置:

<?php $post_excerpts[$counter] = apply_filters('get_the_excerpt', $current_post->post_excerpt); ?>

我想知道为什么有这么多 php 开始和结束标签,所以你可以让你的代码更具可读性:

<?php while ($the_query->have_posts()) : $the_query->the_post();
$current_post = get_post($post->ID);
$post_excerpts[$counter] = apply_filters('get_the_excerpt', $current_post->post_excerpt);
$post_titles[$counter] = get_the_title($post->ID);
$post_permalinks[$counter] = get_the_permalink($post->ID);
$post_thumbs[$counter] = get_the_post_thumbnail($post->ID, '', array('class' => 'img-fluid'));
$counter++;
endwhile; ?>

作为附加信息,您也可以仅使用过滤器,应该与您的帖子对象一起使用:

$post_titles[$counter] = apply_filters('the_title',$current_post->post_title);

编辑:

您可以使用mb_strimwidth将摘录修剪到一定长度(阅读更多:https://www.php.net/manual/en/function.mb-strimwidth.php(:

$current_post = get_post($post->ID);
$trim_excerpt = apply_filters('get_the_excerpt', $current_post->post_excerpt);
$post_excerpts[$counter] = mb_strimwidth($trim_excerpt, 0, 40, '...');

编辑2:

也许你应该检查你是否正在获取你的帖子对象。您总是看到相同的摘录这一事实可能意味着您获得了当前页面的摘录(而不是查询中的帖子(。

$current_id = get_the_id();
$current_post = get_post($current_id);

最新更新