save_post() on Menu Save

When the wordpress menu is saved in the backend, functions hooked on to save_post() run. Is there a way to make these ru

When the wordpress menu is saved in the backend, functions hooked on to save_post() run. Is there a way to make these run only when singular items are saved, and not when the menu is saved?

When the wordpress menu is saved in the backend, functions hooked on to save_post() run. Is there a way to make these run only when singular items are saved, and not when the menu is saved?

Share Improve this question asked Apr 26, 2019 at 10:59 vagu0071vagu0071 32 bronze badges 3
  • Sorry but i am not getting you, What exactly you want !! – Pratik Patel Commented Apr 26, 2019 at 11:11
  • 1 Menus are singular items. Technically. Inside your function you should be checking what kind of post is being saved, and that any data you're expecting exists. If you have code that's causing you trouble, you'll need to share it to get any help. – Jacob Peattie Commented Apr 26, 2019 at 11:42
  • 1 each menu item is a custom post type, you should be checking the post type of the post when the save_post hook runs. Don't assume it only runs for post, it runs for pages, nav menu items, reusable blocks, etc – Tom J Nowell Commented Apr 26, 2019 at 11:49
Add a comment  | 

1 Answer 1

Reset to default 0

As Mr. Peattie and Mr. Nowell pointed out, you should check the post type as one of the first things in your save_post function.

Here's couple of ways how to do it,

add_action( 'save_post', 'prefix_my_save_post_action', 10, 3 );
function prefix_my_save_post_action( $post_id, $post, $update ) {

  // Check for single post type
  if ( 'my_post_type' !== $post->post_type ) {
    return;
  }

  // Check multiple post types with in_array()
  $valid_post_types = array(
    'post' => true,
    'page' => true,
    'post_type_a' => true,
    'post_type_b' => true
  );
  if ( ! in_array( $post->post_type, $valid_post_types ) ) {
    return;
  }
  // or with isset() <-- uses array keys
  if ( ! isset( $valid_post_types[$post->post_type] ) ) {
    return;
  }

  // Do stuff
}

There's also the save_post_{$post->post_type} action that you could use to directly target a certain post type save action.

add_action( 'save_post_my_post_type', 'prefix_my_save__cpt_post_action', 10, 3 );
function prefix_my_save_post_action( $post_id, $post, $update ) {
  // No need to check for post type as it is already in the action
  // Do stuff
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745543468a4632232.html

相关推荐

  • save_post() on Menu Save

    When the wordpress menu is saved in the backend, functions hooked on to save_post() run. Is there a way to make these ru

    6小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信