Magento2: Default to sort by price descending not ascending
Copy the file:
vendor/magento/module-catalog/view/frontend/layout/catalog_category_view.xml
to
app/design/frontend/{{Vender_Namespace}}/{{Theme_Name}}/Magento_Catalog/layout/catalog_category_view.xml
into your theme and add this to the file:
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<referenceBlock name="category.products.list">
<action method="setDefaultDirection">
<argument name="dir" xsi:type="string">desc</argument>
</action>
</referenceBlock>
</referenceContainer>
<move element="category.view.container" destination="content" before="-"/>
</body>
</page>
The links that Manashvi point to the right locations in the core for the files that control this functionality, but they don't provide a solution. I didn't find this anywhere in the core code so i just took a guess based on the code in this file:
vendor/magento/module-catalog/Block/Product/ProductList/Toolbar.php
and used the syntax in other configuration in other .xml files.
I did try calling $block->setDefaultDirection('desc')
in the file:
vendor/magento/module-catalog/view/frontend/templates/product/list/toolbar/sorter.phtml
file but this didn't work. I haven't tracked down why, but using the xml to set the default worked, so i just moved on.
You can use the shorter version as well. For specific categories you can use seperate files: catalog_category_view_id_X.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="category.products.list">
<action method="setDefaultDirection">
<argument name="dir" xsi:type="string">desc</argument>
</action>
</referenceBlock>
</body>
</page>