[resolved] Call function on multiple actions (4 posts)

  1. Mark Senff
    Posted 1 year ago #

    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() );
  2. Mark Senff
    Posted 1 year ago #

    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).

  3. catacaustic
    very awesome
    Posted 1 year ago #

    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');

  4. Mark Senff
    Posted 1 year ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic