0

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

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.