草庐IT

用于从 Magento 中的 sitemap.xml 中排除特定类别页面的 PHP 代码

coder 2024-02-29 原文

我想包含我的 Magento 网站的 sitemap.xml 中不应被搜索引擎编入索引的那些页面。为此,我已将 Catalog/Category.php Cms/Page.php 复制到我相应的 app/code/local 目录中,我正在修改它。

我已成功修改 Page.php 以从我的 sitemap.xml 中排除特定的 CMS 页面。我按照给出的指示 here

由于我不熟悉 PHP,我不知道要使此解决方案适应 Category.php 文件需要做哪些更改。

这是我目前的 Category.php 文件,它不排除我想要从 sitemap.xml 中获取的任何特定类别页面:

 <?php

class Mage_Sitemap_Model_Resource_Catalog_Category extends Mage_Core_Model_Resource_Db_Abstract
{
/**
 * Collection Zend Db select
 *
 * @var Zend_Db_Select
 */
protected $_select;

/**
 * Attribute cache
 *
 * @var array
 */
protected $_attributesCache    = array();

/**
 * Init resource model (catalog/category)
 *
 */
protected function _construct()
{
    $this->_init('catalog/category', 'entity_id');
}

/**
 * Get category collection array
 *
 * @param unknown_type $storeId
 * @return array
 */
public function getCollection($storeId)
{
    $categories = array();

    $store = Mage::app()->getStore($storeId);
    /* @var $store Mage_Core_Model_Store */

    if (!$store) {
        return false;
    }

    $this->_select = $this->_getWriteAdapter()->select()
        ->from($this->getMainTable())
        ->where($this->getIdFieldName() . '=?', $store->getRootCategoryId());
    $categoryRow = $this->_getWriteAdapter()->fetchRow($this->_select);

    if (!$categoryRow) {
        return false;
    }

    $urConditions = array(
        'e.entity_id=ur.category_id',
        $this->_getWriteAdapter()->quoteInto('ur.store_id=?', $store->getId()),
        'ur.product_id IS NULL',
        $this->_getWriteAdapter()->quoteInto('ur.is_system=?', 1),
    );
    $this->_select = $this->_getWriteAdapter()->select()
        ->from(array('e' => $this->getMainTable()), array($this->getIdFieldName()))
        ->joinLeft(
            array('ur' => $this->getTable('core/url_rewrite')),
            join(' AND ', $urConditions),
            array('url'=>'request_path')
        )

        ->where('e.path LIKE ?', $categoryRow['path'] . '/%');

    $this->_addFilter($storeId, 'is_active', 1);

    $query = $this->_getWriteAdapter()->query($this->_select);
    while ($row = $query->fetch()) {
        $category = $this->_prepareCategory($row);
        $categories[$category->getId()] = $category;
    }

    return $categories;
}

/**
 * Prepare category
 *
 * @param array $categoryRow
 * @return Varien_Object
 */
protected function _prepareCategory(array $categoryRow)
{
    $category = new Varien_Object();
    $category->setId($categoryRow[$this->getIdFieldName()]);
    $categoryUrl = !empty($categoryRow['url']) ? $categoryRow['url'] : 'catalog/category/view/id/' . $category->getId();
    $category->setUrl($categoryUrl);
    return $category;
}

/**
 * Add attribute to filter
 *
 * @param int $storeId
 * @param string $attributeCode
 * @param mixed $value
 * @param string $type
 * @return Zend_Db_Select
 */
protected function _addFilter($storeId, $attributeCode, $value, $type = '=')
{
    if (!isset($this->_attributesCache[$attributeCode])) {
        $attribute = Mage::getSingleton('catalog/category')->getResource()->getAttribute($attributeCode);

        $this->_attributesCache[$attributeCode] = array(
            'entity_type_id'    => $attribute->getEntityTypeId(),
            'attribute_id'      => $attribute->getId(),
            'table'             => $attribute->getBackend()->getTable(),
            'is_global'         => $attribute->getIsGlobal(),
            'backend_type'      => $attribute->getBackendType()
        );
    }

    $attribute = $this->_attributesCache[$attributeCode];

    if (!$this->_select instanceof Zend_Db_Select) {
        return false;
    }

    switch ($type) {
        case '=':
            $conditionRule = '=?';
            break;
        case 'in':
            $conditionRule = ' IN(?)';
            break;
        default:
            return false;
            break;
    }

    if ($attribute['backend_type'] == 'static') {
        $this->_select->where('e.' . $attributeCode . $conditionRule, $value);
    } else {
        $this->_select->join(
            array('t1_'.$attributeCode => $attribute['table']),
            'e.entity_id=t1_'.$attributeCode.'.entity_id AND t1_'.$attributeCode.'.store_id=0',
            array()
        )
        ->where('t1_'.$attributeCode.'.attribute_id=?', $attribute['attribute_id']);

        if ($attribute['is_global']) {
            $this->_select->where('t1_'.$attributeCode.'.value'.$conditionRule, $value);
        } else {
            $ifCase = $this->_select->getAdapter()->getCheckSql('t2_'.$attributeCode.'.value_id > 0', 't2_'.$attributeCode.'.value', 't1_'.$attributeCode.'.value');
            $this->_select->joinLeft(
                array('t2_'.$attributeCode => $attribute['table']),
                $this->_getWriteAdapter()->quoteInto('t1_'.$attributeCode.'.entity_id = t2_'.$attributeCode.'.entity_id AND t1_'.$attributeCode.'.attribute_id = t2_'.$attributeCode.'.attribute_id AND t2_'.$attributeCode.'.store_id=?', $storeId),
                array()
            )
            ->where('('.$ifCase.')'.$conditionRule, $value);
        }
    }

    return $this->_select;
} 
}

编辑:非常感谢卢克在下面的评论中!这对我有用。我不得不稍微修改一下代码,因为直到 if 语句之后才定义 $category。

while ($row = $query->fetch()) {

// Added to exclude specific categories
if(in_array($this->_prepareCategory($row)->getId(), $this->ignoreCategories))
{
    continue;
}

$category = $this->_prepareCategory($row);
$categories[$category->getId()] = $category;
}

正如 Luke 所说,我为类别 ID 创建了类属性:

protected $ignoreCategories = array("2","3","16");//Replace the numbers with your category IDs

最佳答案

要获得快速解决方案,请添加以下代码,更好的方法是向类别 EAV 添加一个属性,然后使用它来检查它是否应包含在站点地图输出中。

为了快速破解,为应该忽略的类别 ID 添加一个数组作为类属性,

protected $ignoreCategories = array("2","3","16");

然后在 getCollection() 函数底部附近检查这些 ID,

while ($row = $query->fetch()) {

// Added to exclude specific categories
if(in_array($category->getId(), $this->ignoreCategories)
{
    continue;
}

    $category = $this->_prepareCategory($row);
    $categories[$category->getId()] = $category;

关于用于从 Magento 中的 sitemap.xml 中排除特定类别页面的 PHP 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14062323/

有关用于从 Magento 中的 sitemap.xml 中排除特定类别页面的 PHP 代码的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  6. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  7. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  8. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  9. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐