【问题标题】:saved_post post_updated firing before custom fields are updated, what function fires after custom fields are updated? wordpresssaved_post post_updated 自定义字段更新前触发,自定义字段更新后触发什么函数? WordPress
【发布时间】:2015-03-08 23:38:21
【问题描述】:

我有一个问题,我想使用另一个自定义帖子字段更新自定义用户元数据字段。它必须在整个帖子包括自定义字段保存/更新之后发生。但我发现的所有调用:更新基本帖子数据,然后调用操作,然后更新自定义字段。

saved_post 和 post_updated 导致此代码延迟 1 保存。即,如果我要创建一个新帖子并将 $my_value 设置为 5,我第一次保存它会返回 0,然后下次它会返回 5。等等。

有谁知道在保存自定义帖子数据后运行的动作挂钩?或者如何让 save_post 或 post_updated 在自定义帖子数据之后触发?

    function zhu_li_do_the_thing( $post_id ) {

//获取post数据,提取author-ID和post-Type

$post = get_post( $post_id );
$post_type = $post->post_type;
$userid = $post->post_author;

//如果你是我的自定义帖子类型,则获取我想要的自定义字段值。

if( 'my_custom_post_type' == $post_type ){
  $post_custom_fields = get_post_custom($post_id);
  $my_custom_field = $custom_fields['im_a_field'];
  foreach($im_a_field as $key ){
        $my_value = $key;
        }

// 如果值以“+”或“-”开头,则对作者自定义元数据进行数学运算,如果为 null,则忽略它,如果是其他任何值,则使元数据 = 值。

  if(substr($my_value, 0,1)=='+' || substr($my_value, 0,1)=='-'){
        $my_int = intval($my_value);
        $author_int = intval(get_user_meta($userid, 'the_objective, true)); 
        $result = ($author_int + $str);
        update_user_meta( $userid, 'the_objective', $result );

  }elseif($my_value == null ){
        return;
  }else{ 
        update_user_meta( $userid, 'the_objective', $my_value )
  }}};

add_action( 'save_post, 'zhu_li_do_the_thing' );

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    您应该使用pre_post_update 来检查之前的帖子元,并使用post_updated 来检查更新的帖子元。

    以下是检查woocomerce产品库存状态的类的sn-p代码。

    function __construct()
    {   
        add_action( 'post_updated', array( $this, 'post_updated' ), 1, 1 );
        add_action( 'pre_post_update', array( $this, 'pre_post_update' ), 1, 1 );
    }
    
    function pre_post_update( $post_ID )
    {       
        global $post_type;
    
        if( $post_type == 'product' )
            define( 'stock_status_previous', get_post_meta( $post_ID, '_stock_status', 1 ) );
    }
    
    function post_updated( $post_ID )
    {
        if( defined( 'stock_status_previous' ) )
        {
            $stock_status = get_post_meta( $post_ID, '_stock_status', 1 );
    
            if( $stock_status == stock_status_check )
                return;
    
            // post meta is different - sp do something
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2014-10-11
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2018-07-22
      相关资源
      最近更新 更多