doublesecretagency / craft-viewcount

View Count plugin for Craft CMS
Other
6 stars 4 forks source link

Can't use this with Structures? #6

Closed Coalescent closed 4 years ago

Coalescent commented 4 years ago

I'm trying your plugin and cannot get it to work, as follows...

I query for some structure entries:

{% set articles = craft.entries().section('buArticles').type('buArticle').all() %}

And then try to sort them:

{% do craft.viewCount.sort(articles) %}

And get this error:

Argument 1 passed to doublesecretagency\viewcount\variables\ViewCountVariable::sort() must be an instance of craft\elements\db\ElementQuery, array given, called in localpath/cadex/craft/vendor/twig/twig/src/Extension/CoreExtension.php on line 1495

I've checked articles and it looks like an EntryQuery to me... i.e.

object(craft\elements\db\EntryQuery)#3814 (84) {
  ["editable"]=>
  bool(false)
  ["sectionId"]=>
  array(1) {
    [0]=>
    string(2) "14"
  }
  ["typeId"]=>
  array(1) {
    [0]=>
    string(2) "14"
  } ... etc...

Am I completely missing something or is this a bug or other issue?

Craft 3.4.4 MySQL 5.7.26 PHP 7.3.8 ViewCount 1.0.1

Coalescent commented 4 years ago

So further to this, the error above is returned for any element query passed to the plugin for {% do craft.viewCount.sort(query) %}.

Everything else works as expected in terms of incrementing and tracking counts.

Maybe a 3.4 issue...?

lindseydiloreto commented 4 years ago

Hey @Coalescent, sorry for the late reply! It looks like this is actually a really simple issue...

Adding the .all() converts it from an EntryQuery to an array.

{# EntryQuery #}
{% set articles = craft.entries().section('buArticles').type('buArticle') %}

{# Array #}
{% set articles = craft.entries().section('buArticles').type('buArticle').all() %}

So what you really want to do is something like this...

{# Get the EntryQuery #}
{% set articles = craft.entries().section('buArticles').type('buArticle') %}

{# Sort by most viewed #}
{% do craft.viewCount.sort(articles) %}

{# Loop through articles #}
{% for article in articles.all() %}
    ...
{% endfor %}

Hope that helps, sorry again for the late reply!