2016-10-14 164 views
0

我知道这已经被问过几百次了,但我正在跳过某个步骤,并且如果有人能帮我弄清楚什么是错误的(或者帮助我写得更好),我会很感激它。wpdb用if/else语句foreach循环

我使用wordpress/woocommerce。当用户购买产品时,我将以下内容插入表中:user_id,email,product_id,timestamp。

在每个产品页面上,我试图编写一些循环遍历表的代码来检查用户是否购买了相应的视频;如果是的话,它会显示视频,如果没有,它会显示一些文字。

我的逻辑有点偏离,或者我做得太多,但我试图在codex中关注the example。现在使用下面的代码,它会显示该页面的视频(因为我已经购买了它),但如果我没有,它将不会显示其他文本;我将拥有6-9个视频,所以如果我可以使此代码更高效,我很乐意学习如何。谢谢。这里是我的代码:

global $wpdb; 
$user_id = get_current_user_id(); 

$results = $wpdb->get_results("SELECT * FROM awdwp_webinar_orders WHERE user_id=" . $user_id . ""); 

if ($results) { 
    foreach($results as $result) { 
     $loop_uid = $result->user_id; 
     $loop_pid = $result->product_id;?> 

     if (is_product(991) && $loop_uid == $user_id && $loop_pid == 991) { 
      echo '<h2>' . get_the_title($id) . '<h2>'; 
      $the_video = get_field('video_file'); 
      //display video code 
     } //end if 
    } //end foreach 
} else { 
    echo "please purchase"; 
} 

回答

0
global $wpdb; 
$user_id = get_current_user_id(); 

$results = $wpdb->get_results("SELECT * FROM awdwp_webinar_orders WHERE user_id=" . $user_id . ""); 

if ($results) { 
    foreach($results as $result) { 
     $loop_uid = $result->user_id; 
     $loop_pid = $result->product_id;?> 

     if (is_product(991) && $loop_uid == $user_id && $loop_pid == 991) { 
      echo '<h2>' . get_the_title($id) . '<h2>'; 
      $the_video = get_field('video_file'); 
      //display video code 
     }else{ 
      echo "please purchase"; 
     }//end if 
    } //end foreach 
} else { 
    echo "please purchase"; 
} 
+0

这将显示*购买*为表中的每个条目不匹配的if语句。现在我有两个购买(产品ID = 1017,991),它会显示*购买*和视频文件。 – VCP

0

这种方式解决了这个问题:

global $product; 
global $wpdb; 
$id = $product->id; 
$user_id = get_current_user_id(); 

$results = $wpdb->get_results("SELECT * FROM awdwp_webinar_orders WHERE product_id=" . $id . ""); 

if ($results) { 
    foreach($results as $result) { 
     $loop_uid = $result->user_id; 
     $loop_pid = $result->product_id; 

     if (is_product(991) && $loop_uid == $user_id) { 
      //code 
     } else {} 
    } 
}