Views Work v2.0
Track pageviews and content popularity in Craft CMS
More Craft plugins

Views Work Events

BLOCK PAGEVIEW REGISTRATION EVENT

If you're deeper into development, Views Work exposes an event that allows you to programmatically determine if a page view should be registered or not.

A use case is where you may want to exclude specific pages from registrations, and exclude them from popular content.
Below is example code for a Craft module:


namespace modules;

use Craft;
use twentyfourhoursmedia\viewswork\events\BlockElementViewRegistrationEvent;
use twentyfourhoursmedia\viewswork\services\ViewsWorkService;
use yii\base\Event;

class Module extends \yii\base\Module
{
    /**
     * Initializes the module.
     */
    public function init()
    {
        // Set a @modules alias pointed to the modules/ directory
        Craft::setAlias('@modules', __DIR__);

        parent::init();

        // Example of blocking a pageview when the user agent contains the word 'bot'
        // (to block bots)
        Event::on(
            ViewsWorkService::class,
            ViewsWorkService::EVENT_BLOCK_ELEMENT_VIEW_REGISTRATION,
            static function (BlockElementViewRegistrationEvent $event) {
                //  if the registration was already blocked, don't check any further
                if ($event->blocked) {
                    return;
                }
                // Enter some expression here if the pageview should be blocked.
                // In this case we search for occurrence of the word 'bot' in the user agent to block some bots
                $request = Craft::$app->getRequest();
                $userAgent = strtolower($request->getUserAgent());
                if (str_contains($userAgent, 'bot')) {
                    $event->blocked = true;
                }
            }
        );
    }
}