How to count number of functions attached to an action hook?

Don’t ask me way but i actually have a function to count hooked functions to a tag

/**
 * count_hooked_functions 
 * @author Ohad Raz
 * @param  string $tag hook name as string
 * @return int the number of hooked functions to a specific hook
 */
function count_hooked_functions($tag = false){
    global $wp_filter;
    if ($tag){
        if (isset($wp_filter[$tag])){
            return count($wp_filter[$tag]);
        }
    }
    return 0;
}

but this is an example where a single class would be a much better solution instead of writing the same code over and over something like:

/**
* my_site_notices
* @author  Ohad Raz
*/
class my_site_notices
{
    public $notices = array();
    public $has_notices = false;
    /**
     * __construct class constructor
     * @author  Ohad Raz
     */
    function __construct(){
        add_action('site_notices',array($this,'simple_notification'));
    }

    /**
     * simple_notification 
     * a funciton which prints the added notification at the  site_notices action hook
     * @author  Ohad Raz
     * @access public
     * @return Void
     */
    public function simple_notification(){
        if ($this->has_notices){
            foreach ($notices as $n){
                echo '<div>'.$n.'</div>';
            }
        }
    }

    /**
     * getCount 
     * @author  Ohad Raz
     * @access public
     * @return int  the number of notifications
     */
    public function getCount(){
        return count($this->notices);
    }

    /**
     * add 
     * @param string $n a notification to add
     * @author  Ohad Raz
     * @access public
     * @return void
     */
    public function add($n = ''){
        $this->notices[] = $n;
    }
}//end class
/**
 * Usage: 
 */

global $my_notices;
$my_notices = new my_site_notices();

//to add a notification 
$my_notices->add("this is my first notification");
$my_notices->add("this is my 2nd notification");
$my_notices->add("this is my 3rd notification");

//get the count
$count = $my_notices->getCount();

Leave a Comment