php - save_post post_updated 在更新自定义字段之前触发,更新自定义字段后触发什么函数?文字新闻

标签 php wordpress custom-post-type

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

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

有人知道保存自定义帖子数据后运行的操作 Hook 吗?或者如何使 save_post 或 post_updated 在自定义帖子数据后触发?

    function zhu_li_do_the_thing( $post_id ) {

//获取帖子数据,提取作者ID和帖子类型

$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;
        }

//如果值以“+”或“-”开头,则根据authors-custom-metadata对其进行数学运算,如果为空则忽略它,如果是其他值,则使元数据=该值。

  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' );

最佳答案

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

以下是来自一个类的代码片段,用于检查 woocomerce 产品的库存状态。

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

}

关于php - save_post post_updated 在更新自定义字段之前触发,更新自定义字段后触发什么函数?文字新闻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27881077/

相关文章:

javascript - 如何使用 jQuery 和 Galleria 更新 HTML 元素?

php - 在外部 php 文件中使用 get_option

php - WordPress 按帖子类型对帖子进行排序

wordpress - 您可以将自定义帖子类型帖子设置为 WordPress 中的静态主页吗?

php - 如何使用 MySQLi 查询其中包含撇号的列

PHP 导航栏事件类

css - Wordpress 页眉宽度(Genesis、Foodie Pro)

categories - 从自定义帖子类型循环/存档中排除类别

php - 如何在 .user.ini 中引用主目录

php - 用于显示 mysql 版本 5.0.45 的 mysql 数据库中用户定义函数的代码的 Mysql 查询是什么?