admin管理员组

文章数量:1277303

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?

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?

Share Improve this question asked Oct 14, 2021 at 8:49 icolumbroicolumbro 791 silver badge9 bronze badges 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
 |  Show 3 more comments

1 Answer 1

Reset to default 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' );

本文标签: hooksHow check if a post is saved from backend or frontend