在保存或更新自定义帖子时,我可以在WordPress中使用哪些操作?

Kyl*_*iss 13 php wordpress custom-post-type

有没有什么方法可以自定义帖子的save_post?我的functions.php编码方式是将大量自定义字段添加到普通帖子和不需要/使用它们的页面.

小智 24

WordPress 3.7引入了一种用save_post_{$post_type}钩子处理这个问题的新方法.

假设您的自定义帖子类型是"member-directory".现在,您只能使用以下内容在该帖子类型上运行save_post:

function my_custom_save_post( $post_id ) {

    // do stuff here
}
add_action( 'save_post_member-directory', 'my_custom_save_post' );
Run Code Online (Sandbox Code Playgroud)


Tom*_*ger 15

自3.7.0更新 - 道具@Baptiste提醒

3.7.0引入了" save_post_{$post->post_type}"钩子,它将由帖子类型触发.这允许您添加特定于自定义帖子类型(或"页面"或"发布"等)的操作.这为您节省了以下一行.

接受的方法是添加一个动作save_post_{post-type}({post-type}在上面的例子中替换你的帖子类型的slug ).您可以/可能仍应在操作的回调中执行许多检查,我在下面的示例中记录了这些检查:

来自食典委:

/* Register a hook to fire only when the "my-cpt-slug" post type is saved */
add_action( 'save_post_my-cpt-slug', 'myplugin_save_postdata', 10, 3 );

/* When a specific post type's post is saved, saves our custom data
 * @param int     $post_ID Post ID.
 * @param WP_Post $post    Post object.
 * @param bool    $update  Whether this is an existing post being updated or not.
*/
function myplugin_save_postdata( $post_id, $post, $update ) {
  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
      return;


  // Check permissions
  if ( 'page' == $post->post_type ) 
  {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
  }
  else
  {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
  }

  // OK, we're authenticated: we need to find and save the data

  $mydata = $_POST['myplugin_new_field'];

  // Do something with $mydata 
  // probably using add_post_meta(), update_post_meta(), or 
  // a custom table (see Further Reading section below)

   return $mydata;
}
Run Code Online (Sandbox Code Playgroud)

如果您要注册多个自定义帖子类型,并且希望将save_post功能合并到一个函数中,那么请挂钩通用save_post操作.但是,如果这些帖子类型保存数据的方式有任何差异,请记得在您的函数中进行帖子类型检查.

例如: if ( 'my-cpt-1' == $post->post_type ){ // handle my-cpt-1 specific stuff here ...

  • @Amanda:除了(轻微)性能影响之外,你建议的方法可以工作,并且可能更容易为人类解析,因为你可以将"保存"操作与你定义元数据的相同代码块相关联,保持整洁.另一种方法是为整个主题或插件定义单个"保存"函数回调,甚至可以封装在自己的类或至少一个单独的文件中,然后使用switch语句定义单个元数据保存.编码风格和个人偏好的问题. (3认同)
  • @Baptiste 感谢您的提醒。我已经更新了我的答案。新开发人员应该注意推荐方法包括的额外安全检查 - `save_post_{post-type}` 钩子没有添加任何比通用 `save_post` 钩子额外的安全检查。(它在源代码中直接出现在它的下方 - 所以除了它只在保存该特定帖子类型时触发之外,没有其他逻辑)。 (2认同)