wordpressfishpig

How to set order on custom field with Fishpig


I have events as Wordpress CPT & ACF which have a publish_date (build-in), when they should appear in the news and a start_date (this is the custom field) for displaying in the list and for sorting in a kind of calendar.

Here is my code:

public function getEventsCollection()
{
    $collection = Mage::getResourceModel('wordpress/post_collection');
    $collection->addPostTypeFilter('events');
    $collection->setOrderByPostDate();
    $collection->addIsViewableFilter();
    $collection->setPageSize(20);
    $collection->load();
    return $collection;
}

I can only find the setOrderByPostDate() but no other way to set the order on the custom-field start_date for the post-collection.

The start_date and the publish_date are independent to each other, some events may announced earlier then others.

I tried it already with

$collection->setOrder('start_date');

But I will get an SQL-Error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'start_date' in 'order clause', query was: SELECT...

Solution

  • The custom field 'start_date' is not part of the query so cannot be used for ordering. You can debug the query like so:

    <?php echo $collection->getSelect() ?>
    

    If you take a look in the Abstract Collection file for Fishpig_Wordpress (app/code/community/Fishpig/Wordpress/Model/Resource/Collection/Abstract.php), you will see the following methods which may be of use to you:

    public function resetOrderBy();
    public function addMetaFieldToSelect($metaKey);
    public function addMetaFieldToFilter($metaKey, $filter);
    public function addMetaFieldToSort($field, $dir = 'asc');
    

    If you simply want to sort by the field, the addMetaFieldToSort would look like the correct choice, however if you check the code, this method doesn't actually join the field so this wouldn't work. You could do the following:

    <?php $collection->resetOrderBy() ?>
    <?php $collection->addMetaFieldToSelect('start_date') ?>
    <?php $collection->addMetaFieldToSort('start_date', 'desc') ?>