首页 > 解决方案 > HTML5Blank 将摘录保存到数组中

问题描述

我使用 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]; ?>

标签: phpwordpress

解决方案


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

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

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


我看了一下HTML5-Blank-Theme的functions.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 作为参数。所以也许它只能在 single.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);

推荐阅读