最好的方法是创建一个自定义扩展/模型,有很多教程可以做到这一点,但是你可以使用一些东西来生成一个例子让你开始:
http://www.silksoftware.com/magento-module-creator/
但是,对于这么简单的事情,您可以在本地命名空间中创建一个自定义块,例如:
app/code/local/Mage/Catalog/Block/Product/Ratingsjson.php
<?php
/**
* Ratingsjson.php
*/
class Mage_Catalog_Block_Product_Ratingsjson extends Mage_Catalog_Block_Product_Abstract
{
/**
* Get products with special offer attribute set
*
* @return type
*/
public function getRatings()
{
/**
* This will be injected from the tag / XML below
* you can pass what ever variables you want this way.
* getSomeAttribute() will get the value 'some_attribute' from the
* CMS tag or XML config.
*/
$categoryId = $this->getCategoryId();
if($categoryId == NULL) {
$categoryId = 1; // or some default;
}
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
// Do your stuff here...
$query = "SELECT round(t1.rating_summary / 20) AS rating, t2.product_id FROM review_entity_summary AS t1 INNER JOIN catalog_category_product AS t2 ON t1.entity_pk_value = t2.product_id WHERE category_id =" . $cid . " AND store_id = '1'";
$results = $read->fetchAll($query);
return json_encode($results);
}
}
创建一个模板来做你想做的事:
模板/mymodeule/mytemplate.phtml
<?php
echo $this->getRatings();
然后,您可以在 CMS 页面中使用您的新块:
{{block type="catalog/ratignsjson" category_id="3" temaplte="mymodeule/mytemplate.phtml"}}
或者,如果您想通过 XML 配置加载它:
<block type="catalog/ratignsjson" category_id="3" name="ratignsjson" template="mymodeule/mytemplate.phtml"/>
要正确执行此操作并输出严格的 Json 数据,您需要设置 json 内容类型标头等,但我认为这对于这种特殊情况来说有点太多了。