mrfr
mrfr

Reputation: 1794

How can I re-use my wordpress action hook functions as 'normal' functions

I have an function action hook which collects subscriptions from our database. I want to use this so that I can display the subscriptions on the page, but I also want to use this function in another function that calculates the new subscription price. Is this possible?

My code looks somewhat like this

add_action( 'wp_ajax_get_get_subs_with_type', 'get_subs_with_type' );
add_action( 'wp_ajax_nopriv_get_get_subs_with_type', 'get_subs_with_type' );

function get_subs_with_type($sub_type) {
    $subs = //get alot of info from database......
    echo $subs;
}

But I also want to use this function with a return statement instead of echo to be used in another function.

functon calc_subs(){
    $subs = get_subs_with_type();
    return $subs[1]->price + 1;
}

So can I use a function tied to an action hook as a 'normal' function as well? Or what should I do?

EDIT:

If there is no good way of doing this, I made a little hacky solution:

add_action( 'wp_ajax_get_get_subs_with_type', 'get_subs_with_type' );
add_action( 'wp_ajax_nopriv_get_get_subs_with_type', 'get_subs_with_type' );

function get_subs_with_type($sub_type) {
    $subs = get_sub_from_db()
    echo $subs;
}

function get_sub_from_db() {
    $subs = //get alot of info from database......
    return $subs;
}

Now I can use get_sub_from_db() in my other function as well.

functon calc_subs(){
    $subs = get_sub_from_db();
    return $subs[1]->price + 1;
}

What do you think of this?

Upvotes: 0

Views: 29

Answers (2)

Kamil Adryjanek
Kamil Adryjanek

Reputation: 3338

You can for example do something like:

/**
 * Returns bla bla bla
 * @return array 
 */
function get_subs_with_type($sub_type) {
    $subs = //get alot of info from database......
    return $subs;
}

add_action( 'wp_ajax_get_get_subs_with_type', function () {
    echo get_subs_with_type();
});

but remember that while using anonymous function you will not be able to remove this action with remove_action.

Upvotes: 1

jminguely
jminguely

Reputation: 93

The solution you proposed, by creating two different function, one returning the database call & the other calling the first one looks quite good.

Don't forget to add a wp_die(); function after you echoed all this information to the ajax handler. This is required to terminate any ajax call immediately and return a proper response.

Upvotes: 0

Related Questions