仅在条件下运行函数

时间:2017-05-17 10:53:07

标签: 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->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中,管理员只需发布/批准帖子

现在正在发生的事情是,无论如何,如果管理员点击发布功能运行并更新帖子元数,我不想更新帖子元数据,除非发布帖子的管理员是该帖子的当前所有者/作者,如果批准/发布帖子的管理员不是帖子作者,则该帖子刚刚发布而没有任何元数据更新

1 个答案:

答案 0 :(得分:0)

确定解决方案是按照调用操作的顺序,并且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');