Two functions with different arguments and add_actions, but identical code

I feel like this is simple.

I have two functions that contain identical code, but need to have different add_actions and arguments. There’s got to be a way to do this so I’m not copying and pasting between the two when I want to add more code, plus you’re not supposed to duplicate code. What am I missing?

One is for ACF and fires when updating a post type and one is for Admin Columns that fires the same actions but when editing the same post type inline. I have these in a plugin file if that helps.

    function acp_editing_saved_usage1( ACColumn $column, $post_id, $value ) {

runs same code

    }
    add_action( 'acp/editing/saved', 'acp_editing_saved_usage', 10, 3 );


    function my_acf_save_post( $post_id ) {

runs same code

    }
    add_action('acf/save_post', 'my_acf_save_post');

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If I am not missing something here, you could have a third/main function, with two different wrappers for it.

function wpse381184_main(){
    //do your thing!
}

function acp_editing_saved_usage1( ACColumn $column, $post_id, $value ) {
    // call wpse381184_main()
    wpse381184_main();
}
add_action( 'acp/editing/saved', 'acp_editing_saved_usage', 10, 3 );
function my_acf_save_post( $post_id ) {
    // call wpse381184_main()
    wpse381184_main();
}
add_action('acf/save_post', 'my_acf_save_post');

If you need wpse381184_main to use different number of arguments depending on the calling wrapper, you could structure it with the case with more arguments, and simply ignore some arguments depending which hook called it, by using the current_filter() function.

function wpse381184_main($post_id, $hook, ACColumn $column, $value){
    if( 'acp/editing/saved' ===  $hook){
        //do your thing in case A and exit!
        return;
    }
    // do your thing in "default" case B!
}

function acp_editing_saved_usage1( ACColumn $column, $post_id, $value ) {
    // call wpse381184_main()
    wpse381184_main($post_id, current_filter());
}
add_action( 'acp/editing/saved', 'acp_editing_saved_usage', 10, 3 );
function my_acf_save_post( $post_id ) {
    wpse381184_main($post_id, current_filter());
}
add_action('acf/save_post', 'my_acf_save_post');


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x