2014-12-23 39 views
2

我想要做的是在Wordpress中查詢和總結當前登錄用戶的自定義字段。總和自定義字段僅適用於當前用戶 - Wordpress

我有一個寫作公司的網站,讓作家登錄並聲稱他們想要做的工作。對於每個作業,都有一個稱爲「字數」的字段,在該字段中輸入需要完成的文章的字數。爲了計算每個作者對於作業的欠缺程度,我使用單詞計數字段(使用元密鑰「assignment_word_count」)並將其乘以每個作者每字支付的統一費率。

到目前爲止,我放在一起的最接近的腳本就是我想要的,它是一個SQL腳本。不幸的是,它彙總了所有的字數字段,而不僅僅是屬於當前用戶的字段。如果我嘗試向代碼添加任何內容以將其限制爲當前用戶,則總數將降至零。

<?php 
$now = current_time('mysql'); 
       $sql = "SELECT "; 
       $sql .= "meta_value FROM $wpdb->posts AS posts, $wpdb->postmeta AS postmeta "; 
       $sql .= "WHERE posts.ID = postmeta.post_id AND postmeta.meta_key =  'assignment_word_count' "; 
       $sql .= "AND posts.post_status = 'paid' "; 
       $sql .= "AND posts.post_date < '$now' "; 
       $sql .= "AND postmeta.meta_value != '' "; 
       $results = array(); $values = array(); 
       $results = $wpdb->get_results($sql); 
       $totalpay = 0; 
       if (!empty($results)){ 
        foreach ($results as $result) { 
         $totalpay += $result->meta_value; 
        } 
       } 
       echo 'Total Paid: $' . $totalpay * money_format('0.0040=(#10.2n', $number); 
?> 

還有另一個腳本,我發現應該做我正在尋找的,但它告訴我,implode行是一個無效的參數。

<?php 
     //get current user 
     global $current_user; 
     get_currentuserinfo(); 
     // build query of ids by user 
     $userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'assignments')); //change this 

     // loop to create array of ids by user 
     foreach ($userPosts as $post) { 
      setup_postdata($post); 
      $ids[] = get_the_ID(); 
     } 
     $idList = implode(",", $ids); //tun this crap into a list 

     $meta_key = 'assignment_word_count';//set this to your custom field meta key 
     $totalpay = $wpdb->get_col($wpdb->prepare(" 
              SELECT meta_value 
              FROM $wpdb->postmeta 
              WHERE meta_key = %s 
              AND post_id in (" . $idList . ")", $meta_key)); 
     echo 'Total pay: $ ' . array_sum($totalpay); ?> 
+1

那麼格式化你在做什麼,以及預期效果的問題和內容,並簡要陳述。我們只是不知道哪個字段包含您想要限制的用戶ID。 – xQbert

+0

您的查詢沒有作者的參考。你需要像'$ sql。=「和author ='$ current_user'」;'在那裏。正如@ xQbert所說,我們不知道你的列或變量名稱,所以你將不得不適應它。 – Turophile

+0

現在沒有提及作者,因爲我無法讓它正常工作。用戶標識應該是當前用戶。當我在其中添加$ sql。=「和author ='$ current_user'」時,它會使所有其他查詢結果消失,並且根本不顯示任何總計,甚至沒有顯示任何總計的「Total Paid:$」部分回聲。 –

回答

0

您應該先嚐試用硬編碼的用戶標識修復您的查詢,然後再次嘗試如何傳遞當前用戶。

在查詢中,正確的字段名稱是post_author,而不是作者。

相關問題