1

I'm trying to display javascript code if a user is on category page, however my code is displaying on all the pages including product page.

<?php
$_category = Mage::registry('current_category');

if ($_category->getId()) {
      echo '<script>
jQuery(function($){
var url = window.location.href; 
window.location.href = url+"#dir=desc&order=bestsellers";
});
</script>';
}
  else {

      echo '';
  }


?>
2
  • your code is working fine. what do you want to achieve ?
    – Arunendra
    Commented Mar 7, 2016 at 11:13
  • Yeah, my code is working fine on category but I don't want it to work on other pages such as product pages, cms, etc. So only category page. Commented Mar 7, 2016 at 11:16

3 Answers 3

1

create a new js file with your js code in it and add it into your js in the skin in your theme.

and in your local.xml file add the following code

<catalog_category_layered>
    <reference name="head">
        <action method="addItem"><type>skin_js</type><name>js/yourjs.js</name</action>
  </reference>
</catalog_category_layered>
0

To determine if you're on a category page, use:

$frontEnd = Mage::app()->getFrontController();

if ($frontEnd->getRequest()->getRouteName() === 'catalog' && $frontEnd->getAction()->getFullActionName() === 'catalog_category_view') {
1
  • I tried.. It's not working Commented Mar 7, 2016 at 11:30
0

Try Below code :

    <?php
    $_category = Mage::registry('current_category');
     $currentAction = Mage::app()->getRequest()->getControllerName(); 
    if ($currentAction == 'category') {
      echo '<script>
    jQuery(function($){
     var url = window.location.href; 
    window.location.href = url+"#dir=desc&order=bestsellers";
    });
    </script>';
    }
      else {

          echo '';
      }

    ?>
8
  • There was a minor issue in my code i have fixed it.Please try and let me know if its work for you.
    – Arunendra
    Commented Mar 7, 2016 at 11:30
  • its not working.. Commented Mar 7, 2016 at 11:30
  • Have you tried my updated code ?
    – Arunendra
    Commented Mar 7, 2016 at 11:33
  • Yes Arunendra, your code is giving error Call to a member function getId() on a non-object Commented Mar 7, 2016 at 11:40
  • Remove $_category->getId() from if condition see updated answer
    – Arunendra
    Commented Mar 7, 2016 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.