Php 仅当条件满足时运行函数

Php 仅当条件满足时运行函数,php,function,if-statement,Php,Function,If Statement,我只想在当前登录用户是文章作者的情况下运行此功能 global $user_ID; $admin_user = get_user_by( 'id', $user_ID ); $selected = empty( $post->ID ) ? $user_ID : $post->post_author; function return_custom_price( $post ) { global $post; $new_total = get_post_meta( $post-&

我只想在当前登录用户是文章作者的情况下运行此功能

global  $user_ID;
$admin_user = get_user_by( 'id', $user_ID );
$selected   = empty( $post->ID ) ? $user_ID : $post->post_author;

function return_custom_price( $post ) {
global $post;
$new_total = get_post_meta( $post->ID, '_total_egp', true);
$price = get_post_meta($post->ID, '_regular_price', true);
//$sale_price = get_post_meta($post->ID, '_sale_price', true);
$now_price = get_post_meta($post->ID, '_price', true);
$woo_usd_rate = get_post_meta( $post->ID, '_usd_rate', true);
$woo_price_usd = get_post_meta( $post->ID, '_price_usd', true);
$cog = $woo_price_usd * $woo_usd_rate;

if($user_ID == $selected ){

update_post_meta($post->ID, '_regular_price', $new_total);
update_post_meta($post->ID, '_sale_price', '');
update_post_meta($post->ID, '_price', $new_total);
update_post_meta( $post->ID, '_wc_cog_cost', $cog );

}
}

add_action('save_post', 'return_custom_price');
这是我尝试过的,但它不起作用,而且它还是运行了

我想做的是 当用户从前端使用woocommerce发布到wordpress时,发布的帖子将以草稿状态添加到wordpress,管理员只需发布/批准帖子


现在发生的事情是,无论如何,如果管理员单击发布函数运行并更新帖子元,我不想更新帖子元,除非发布帖子的管理员是帖子的当前所有者/作者,并且如果批准/发布帖子的管理员不是帖子作者,发布帖子时没有任何metas更新

确定解决方案是按照调用操作的顺序进行的,并且save_post会在更新帖子时运行,而不会应用任何检查

因此,这可能是一个解决方案

function return_custom_price( $post ) {
global  $post;
$market = get_post_meta( $post->ID, 'market', true);
if($market == "" ){
    return;
}
$new_total = get_post_meta( $post->ID, '_total_egp', true);
$price = get_post_meta($post->ID, '_regular_price', true);
//$sale_price = get_post_meta($post->ID, '_sale_price', true);
$now_price = get_post_meta($post->ID, '_price', true);
$woo_usd_rate = get_post_meta( $post->ID, '_usd_rate', true);
$woo_price_usd = get_post_meta( $post->ID, '_price_usd', true);
$cog = $woo_price_usd * $woo_usd_rate;

update_post_meta($post->ID, '_regular_price', $new_total);
update_post_meta($post->ID, '_sale_price', '');
update_post_meta($post->ID, '_price', $new_total);
update_post_meta( $post->ID, '_wc_cog_cost', $cog );
}   
add_action('save_post', 'return_custom_price');

看起来你的$post->ID从来没有空过。你需要寻找其他字段,把你的var_dumps()放在这里,我建议你不要使用全局变量。另外:你的例程有一个安全漏洞,如果你只想在用户是作者的情况下更新帖子,如果帖子->ID不存在,你需要终止例程,而不是通过。从$select中取出$user\u ID。我需要全局变量,因为我在循环之外