php - WordPress 查询。正确引用页面摘录?

标签 php mysql wordpress

坚持使用 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 page 的例子中您可以看到如何使用 setup_postdata。

另请注意,它在 get_the_excerpt page 上说该函数的参数已弃用。

关于php - WordPress 查询。正确引用页面摘录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8893882/

相关文章:

css - 居中对齐导航项

php - MySQL 请求有效,但在 WordPress 上无效

php - wordpress 中的 AJAX 和 PHP 循环进度

正则表达式 : lookbehind and lookahead and greediness problem

php - Twitter API 返回错误 215,错误的身份验证数据

关于表的 mysql 详细信息

mysql - 为什么列表大小显示为零?

Php年月计算

php - 正则表达式帮助 : how to match only either pattern in a regex that contains "or" operator?

mysql - Google Cloud MySQL 基于行的复制数据类型错误