WordPress挂钩在显示邮政编辑页面之前要编辑元数据



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

我一直在看'load-post.php'挂钩,但是在加载帖子之前,这是调用的(如果我正确理解了),因此POST ID和META数据为无效。我已经尝试了其他钩子,但是我无法完成这项工作。

以下元字段需要在显示在"编辑"页面上之前更改。

$ post_price = get_post_meta(get_the_id(),'price',true); 

示例:Price =数据库中的10个,但我希望它在"邮政编辑"页面上显示时价格= 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
}

这是正确的方式吗?

我发现的最好的钩子是使用 $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
   }
}

edit:好吧,我认为您只需要使用Post的ID即可。如果您需要更改帖子对象(已经从数据库加载并准备打印),则可以使用" the_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'

不是必需的,但是您应该确定要运行此代码的哪种帖子(基于帖子类型,类别,元场等)。没有它,每次都会在管理查询中执行。该代码未进行测试,如果有问题随意报告。

最新更新