How can I access the updated value of a class variable that changes after add_filter is run?

First, thanks in advance for any assistance.

I’m working on an existing project where we’re running a filter on the_content to insert ads after a specific number of paragraphs. Recently, we introduced ACF fields, into which we want to continue the ad insertions. In order to track the number of ads inserted, I have things set up as follows after reading a few articles on what I believe to be similar cases of keeping up with a variable’s state.

As things are now, ads are inserting as expected on the_content but I can’t quite nail down how to ensure that when I follow with ad insertions on ACF content I’m getting the updated $adCounter value.

I feel like I’m close, but obviously not quite there.

functions.php

use ManagersContentManager;
$contentManager = new ContentManager();
$contentManager->run();

ContentManager.php

class ContentManager
{
public function run() {
$insertAfterParagraphs = [5, 13, 23];
$AdManager = new ContentInlineAdManager;

foreach($insertAfterParagraphs as $p) {
add_filter(‘custom_filter_on_the_content’,
[ $AdManager::getInstance(), ‘injectInlineAdTheContent’ ]
);
}

// This returns 1, where I would hope it returns the updated count.
var_dump($AdManager::getInstance()->getAdCount());

// Ad insertion logic for ACF fields to follow.

}
}

InlineAdManager.php

if ( !class_exists( ‘InlineAdManager ‘ ) ) {
class InlineAdManager
{
private $Ad;
private $adCounter;
private static $instance;

public function __construct() {
$this->Ad = new ModelsAd();
$this->adCounter = 1;
}

public static function getInstance() {
if(is_null(self::$instance)) {
self::$instance = new self();
}

return self::$instance;
}

// Run ad insertion logic on the_content.
public function injectInlineAdTheContent() {

$this->adCounter++;
}

// Run ad insertion logic on ACF content.
public function injectInlineAdACFContent() {

$this->adCounter++;
}

public function getAdCount() {
return $this->adCounter;
}
}
}

Read more here:: How can I access the updated value of a class variable that changes after add_filter is run?

Leave a Reply

Your email address will not be published. Required fields are marked *