add_action in class and use it in theme

I’m programming a plugin in WordPress and want to access some database functions with in my theme with the do_action feature. First I just included $fdb-> get_finaboo_footer(1); on my page for example but he couldnt find the object. I added global $fdb; Then it worked. But I dont want to globalize on every php file the $fdb. So I thought I do it with the do_action feature. The Problem is I just get “null” in my var dump.

<?php
/**
* Database Functions
*/

class fdb {
    public function __construct() {
        global $wpdb;
        $this->wpdb = &$wpdb;
        add_action('finaboo_footer', array ( &$this, 'get_finaboo_footer'));
    }


    public function get_finaboo_footer($footer_id) {
        $sql =  $this->wpdb->prepare( "SELECT * FROM wp_finaboo_content_footer WHERE footer_id = '$footer_id' ORDER BY option_id ASC;" );
        $results = $this->wpdb->get_results($sql, ARRAY_A );
        return($results);
    }
}

$fdb = new fdb();

?>

And this would be my call in the theme php files:

Read More
<?php $footer1 = do_action('finaboo_footer', '1'); ?>

don’t know why it dosent work 🙁

Also I’m open for suggestions if this is not the smartest way in WordPress 🙂

Thanks for help

Related posts

Leave a Reply

2 comments

  1. I recommend to add a static method to access the plugin instance.

    Example, taken from this answer:

    class My_Plugin
    {
        private $var = 'foo';
    
        protected static $instance = NULL;
    
        public static function get_instance()
        {
            // create an object
            NULL === self::$instance and self::$instance = new self;
    
            return self::$instance; // return the object
        }
    
        public function __construct()
        {
            // set up your variables etc.
        }
    
        public function foo()
        {
            return $this->var;
        }
    }
    
    // create an instance on wp_loaded
    add_action( 'wp_loaded', array( 'My_Plugin', 'get_instance' ) );
    

    In your theme you can access foo() now like this:

    print My_Plugin::get_instance()->foo();
    

    do_action() never returns something. You would need apply_filters():

    $footer1 = apply_filters( 'finaboo_footer', 1 );
    
  2. I think you need to add a parameter to your add_action call that tells it how many parameters the function accepts (1 in this case):

    add_action('finaboo_footer', array ( &$this, 'get_finaboo_footer'), 1, 1);
    

    add_action( $tag, $function_to_add, $priority, $accepted_args );