繁体   English   中英

Magento 2 / Wordpress / Fishpig相关文章

[英]Magento 2/Wordpress/Fishpig related posts

我目前正在尝试在文章页面(文章后)上检索相关文章的列表。 我在/Block/Post/ListPost.php创建了一个新函数

public function getRelatedPosts()
{
    $posts = $this->getPosts();

    die($this->getCategoryId());

    return $this->_postCollection;
}

但是,当我尝试输出getCategoryId ,我什么也没得到。 我也不确定如何将类别过滤器应用于帖子集。

有人可以在这里建议吗?

我不确定您从何处获取了getCategoryId方法,但这不是ListPost块类的一部分,因此将无法使用。 您不能只发明这样的方法。

您应该检查块类以了解哪些方法可用。 一个简单的方法甚至不需要加载文件,就是将以下PHP添加到类中:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM