0

I created a custom post type called wasb_contact which can be inserted and edited both from the backend and from the frontend (through a form I created). The CPT has some custom meta fields which are saved by a function called wasb_contact_save_postdata and invoked by the save_post_{$post->post_type} hook. I would like this function to be invoked only when the CPT is created or modified from the backend and not also when it is created or modified from the frontend.

How can I do?

8
  • I'd try is_admin() if you haven't already, but I don't know if that'll still be true from the frontend depending on how you're including the admin files to update the posts.
    – Rup
    Commented Oct 14, 2021 at 9:12
  • 2
    To be creatable/editable from the frontend you need some custom code, right? Why not add a flag / specific setting in there, so you know when this is not present, the request is coming from the backend.
    – kero
    Commented Oct 14, 2021 at 9:21
  • I tried with is_admin() but it doesn't work in my case. There isn't a better way than add a flag?
    – icolumbro
    Commented Oct 14, 2021 at 10:33
  • I'm surprised - how is current_screen getting set in your front-end form? How about if ( defined( 'WP_ADMIN' ) ) ? But this all depends on how you've set up the front end form I suppose.
    – Rup
    Commented Oct 14, 2021 at 10:41
  • @Rup it's a simple HTML form in a template. Can you explain the correct use of is_admin(), current_screen, etc, please?
    – icolumbro
    Commented Oct 14, 2021 at 10:54

1 Answer 1

1

I would add some hidden input field to frontend form, and check for its presence in the save_post hook.

...
<input type="hidden" name="saved-on-frontend" value="1">
...

And then check for it in that hooked function:

function my_save_hook() {

    if( isset( $_POST['saved-on-frontend'] ) ) {
        return; // don't do anything ... 
    }

}
add_action( 'save_post_CUSTOM_POST_TYPE', 'my_save_hook' );

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.