Question

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( AC\Column $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');
Was it helpful?

Solution

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( AC\Column $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, AC\Column $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( AC\Column $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');
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top