Support » Plugins » Hacks » Call function on multiple actions

  • Resolved Mark Senff

    (@senff)


    I’m writing some function that needs to be executed every time something changes in the list of posts. So, whenever:
    – a new post is published
    – an existing post is edited
    – an existing post is deleted

    I was thinking to do it like this:

    add_action('publish_post', myfunction());
    add_action('post_updated', myfunction());
    add_action('deleted_post', myfunction());

    I think the second one is not even necessary (it’s executed with publish_post anyways) but is there a better way to do this, instead of calling the function in various situations?

    Is it possible to do something like this (not literally, but structure-wise)?

    add_action( ('publish_post' OR 'post_updated' OR 'deleted_post') , myfunction() );
Viewing 3 replies - 1 through 3 (of 3 total)
  • I guess in this case, this would do the trick:

    add_action('save_post', myfunction());

    However, I’m still interested in how to fire a function with multiple actions (e.g. when a post is updated OR when a user is updated).

    You’ve got it right, you need to have a call to add_action() for each trigger that you need. There’s no way around that at this point. If you get to the point where you have a big list of actions to add you can always set them up in an array and use a foreach() loop to call them all in turn.

    Only one thing that I saw in your code that I’m thinking may not be in your final code?

    add_action('save_post', myfunction());

    That’s not the right way to do it. That would actually call the function at that point, and not when the action hook is called. It should be:

    add_action('save_post', 'myfunction');

    You’re right, I didn’t mean to use myfunction() in there. Not sure why I did, just got confused I guess.

    Thanks for confirming — I figured it would be like that and I guess sometimes it’s just about finding the right (or most efficient) action to pick.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Call function on multiple actions’ is closed to new replies.