Created
December 10, 2019 22:23
-
-
Save piotrpog/9fcc6b6bb5b838d64ed5075003d2f820 to your computer and use it in GitHub Desktop.
Example mofule using incognito field - "favourite category". More info: http://craftsnippets.com/articles/using-incognito-field-plugin-for-craft-cms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// place this code in module variable file | |
public $userFieldHandle = 'visitedarticles'; | |
public $categoryFieldHandle = 'articleCategory'; | |
public function saveArticleVisit($article){ | |
$user = Craft::$app->getUser()->getIdentity(); | |
if(!is_null($user)){ | |
$visitedJSON = $user->getFieldValue($this->userFieldHandle); | |
$visitedIds = (array) json_decode($visitedJSON); | |
if(is_null($visitedIds)){ | |
$visitedIds = array($article->id); | |
$user->setFieldValue($this->userFieldHandle, json_encode($visitedIds)); | |
Craft::$app->elements->saveElement($user); | |
} | |
if(is_array($visitedIds) && !in_array($article->id, $visitedIds)){ | |
$visitedIds[] = $article->id; | |
$user->setFieldValue($this->userFieldHandle, json_encode($visitedIds)); | |
Craft::$app->elements->saveElement($user); | |
} | |
} | |
} | |
public function getMostVisited(){ | |
$user = Craft::$app->getUser()->getIdentity(); | |
if(!is_null($user)){ | |
$visitedJSON = $user->getFieldValue($this->userFieldHandle); | |
$visitedIds = (array) json_decode($visitedJSON); | |
if(is_array($visitedIds)){ | |
$entries = craft\elements\Entry::find()->id($visitedIds)->all(); | |
$categoryIds = []; | |
foreach ($entries as $key => $entry) { | |
if($entry->{$this->categoryFieldHandle}->exists()){ | |
$category = $entry->{$this->categoryFieldHandle}->last(); | |
$categoryIds[$key] = $category->id; | |
} | |
} | |
if(!empty($categoryIds)){ | |
$count = array_count_values ($categoryIds); | |
arsort($count); | |
$keys = array_keys($count); | |
$popularCategory = craft\elements\Category::find()->id($keys[0])->one(); | |
return $popularCategory; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment