Magento 2/Wordpress/Fishpig 相关帖子

Magento 2/Wordpress/Fishpig related posts

我目前正在尝试检索 post 文章页面上的相关 post 列表(post 单篇)。我在 /Block/Post/ListPost.php

中创建了一个新函数
public function getRelatedPosts()
{
    $posts = $this->getPosts();

    die($this->getCategoryId());

    return $this->_postCollection;
}

然而,当我尝试输出 getCategoryId 时,我什么也没得到。我也不确定如何将类别过滤器应用于 post 集合。

有人可以在这里提供建议吗?

我不确定您从哪里获得 getCategoryId 方法,但这不是 ListPost 块 class 的一部分,因此无法使用。你不能只发明这样的方法。

您应该检查块 class 以了解可用的方法。一种甚至不加载文件的简单方法是将以下 PHP 添加到 class:

echo sprintf('<pre>%s</pre>', print_r(get_class_methods($this)));
exit;

您没有指定 post 应该以何种方式相关,但我猜您想从同一类别中获取 post。一种选择是加载 post 的主要类别,然后基于此获取 post 集合。如果您查看 Post class 文件,您将看到 getParentTerm($taxonomy) 方法。

if ($category = $post->getParentTerm('category')) {
    $relatedPosts = $category->getPostCollection();

    // Remove the current post from the collection
    $relatedPosts->addFieldToFilter('ID', array('neq' => $post->getId()));
}

您应该始终查看您正在使用的 class 文件。这就是开源的美妙之处。您可以从字面上看到每个对象可用的方法,甚至可以看到它们是如何工作的。