Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

php - How do do_action and add_action work?

I am trying to find what exactly do_action and add_action works. I already examine with add_action but for do_action i am trying as new now. This what i tried.

function mainplugin_test() {

$regularprice = 50;

if(class_exists('rs_dynamic')) {
$regularprice = 100;
}

// and doing further
//like i echoing the regular price
echo $regularprice; //It print 100 from this code

}

Now instead of placing few code in main file i am planning to create do_action to avoid code messing issue.

    function mainplugin_test() {

    $regularprice = 50;

    do_action('testinghook');

// and doing further
//like i echoing the regular price
echo $regularprice; //It should print 100 but it print 50

    }

so i created another function to point out that hook as something like

function anothertest() {
if(class_exists('rs_dynamic')) {
$regularprice = 100;
}
}
add_action('testinghook','anothertest');

Not sure how to add the lines of code to that hook that above function may work? As per i tried in my testing environment nothing helps. If i understand correct do_action is more like including a file??? If not please advise me.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

do_action creates an action hook, add_action executes hooked functions when that hook is called.

For example, if you add the following in your theme's footer:

do_action( 'my_footer_hook' );

You can echo content at that location from functions.php or a custom plugin:

add_action( 'my_footer_hook', 'my_footer_echo' );
function my_footer_echo(){
    echo 'hello world';
}

You can also pass variables to a hook:

do_action( 'my_footer_hook', home_url( '/' ) );

Which you can use in the callback function:

add_action( 'my_footer_hook', 'my_footer_echo', 10, 1 );
function my_footer_echo( $url ){
    echo "The home url is $url";
}

In your case, you're probably trying to filter the value based on a condition. That's what filter hooks are for:

function mainplugin_test() {
    echo apply_filters( 'my_price_filter', 50 );
}

add_filter( 'my_price_filter', 'modify_price', 10, 1 );
function modify_price( $value ) {
    if( class_exists( 'rs_dynamic' ) )
        $value = 100;
    return $value;
}

Reference

Edit (updated references links)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...