Wordpress查询.正确引用页面的摘录


Wordpress query. Correctly referencing the excerpt for a page?

被Wordpress查询卡住。。。我想做的事情显而易见……但有一句话我就是记不清,也找不到任何关于它的在线信息……

我已经标记了代码的摘录行,我认为这是造成问题的原因。摘录的正确参考文献是什么?

$posts = get_posts(array(
'numberposts' => 2,
'post_type' => 'page',
'meta_key' => 'front_page_feature',
'meta_value' => '1'
));
if($posts)
{
echo '<ul>';
foreach($posts as $post)
{
    echo '<li><article><a href="' . get_permalink($post->ID) . '"><h2>' . get_the_title($post->ID) . '</h2>';
    $excerpt = get_post_excerpt($post->ID); <<<<<<<<<<<<----- HERE
    if (strlen($excerpt) > 135) {
    $excerpt = substr($excerpt, 0, 135) . '...';
            }
echo '<p>'. $excerpt .'</p>';
    echo '</a></article></li>';
}
echo '</ul>';
}

感谢

我可能错了,但foreach中的$post变量不是对象吗?如果是的话,你可以做$post->post_excerpt;

编辑:在深入研究之后,我发现这是行不通的。但是你可以很容易地调整你的脚本,使其按照你想要的方式工作

foreach($posts as $post){
    setup_postdata($post);
    $excerpt = get_the_excerpt(); 
    if (strlen($excerpt) > 135) {
       $excerpt = substr($excerpt, 0, 135) . '...';
    }
    printf(
        '<li><article><a href="%s"><h2>%s</h2><p>%s</p></a></article></li>', 
        get_permalink(), 
        get_the_title(),
        $excerpt
    );
}

我还没有测试过,但它应该可以工作。

在get_post页面的示例中,您可以看到setup_postdata是如何使用的。

另外请注意,它在get_the_excerpt页面上表示,函数的参数已弃用。