在显示 post 编辑页面之前编辑 post 元数据的 Wordpress 挂钩

Wordpress hook to edit the post meta data before displaying a post edit page

我正在尝试在 post 的元数据显示在屏幕上之前编辑该字段。

我一直在查看 'load-post.php' 挂钩,但这是在加载 post 之前调用的(如果我理解正确的话),所以 post id 和元数据为空。 我试过其他钩子,但我没能做到这一点。

以下 post 元字段需要更改才能显示在编辑页面上。

$post_price = get_post_meta(get_the_ID(), 'price', TRUE);

示例:数据库中的 Price = 10,但我希望它在 post 编辑页面上显示时为 Price = 15。

非常感谢任何链接、提示和想法。 :)

编辑:
我目前的解决方案:

add_action('load-post.php','calculate_price');
function calculate_price(){
    $post_id = $_GET['post'];
    //get price from post by post_id and do stuff
}

这是正确的方法吗?

编辑: 好的,我认为您只需要使用 post 的 ID。如果您需要更改 post 个对象(已经从 db 加载并准备打印),您可以使用 'the_post' 代替。由于您只需要访问 post id,我会这样做:

function my_the_post_action( $post ) {
    $screen = get_current_screen();
    if( is_admin() && $screen->parent_base == 'edit' && get_post_type() == 'product' ) {
        $post_id = $post->ID;
        $price = (int) get_post_meta( $post_id, 'price', true );
        update_post_meta( $post_id, 'price', $price + 5 );
    } 
}
add_action( 'the_post', 'my_the_post_action' );

这部分:

get_post_type() == 'product'

不是必需的,但是你应该确定你想要 运行 这段代码是针对哪种 post(基于 post 类型、类别、元字段等) .如果没有它,每次在管理查询中都会执行。此代码未经测试,如有错误,请随时报告。

我找到的最好的钩子是 load-post.php 使用 $current_screen

对于 Woocommerce 产品,有效:

add_action('load-post.php', "calculate_price" );

function calculate_price( ){
   global $current_screen;
   if( is_admin() && $current_screen->post_type === 'product' ){
       $post_id = (int) $_GET['post'];
       $post = get_post( $post_id );
       //Do something
   }
}