2016-01-14 151 views
0

我必須編輯某人的代碼,並且我不熟悉使用它們的方法查詢帖子。我試圖編輯查詢到各種替代品,但我沒有運氣。我想要更改以下查詢以從名爲'job_cat'的定製分類中選擇數據,其中值等於POST值。代碼如下:WordPress自定義查詢分類標準

$querystr = " 
SELECT DISTINCT wposts.* 
FROM $wpdb->posts wposts 
LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id 
LEFT JOIN $wpdb->postmeta wpostmeta2 ON wposts.ID = wpostmeta2.post_id 
LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id) 
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) 
WHERE wp_term_taxonomy.term_id = 94"; 
// If a job type is set and not equal to nothing or any jobs 


if(isset($_POST['search-location']) && $_POST['search-location'] !== "" &&  $_POST['search-location'] !== "All") { 
    $querystr .= " AND (wpostmeta2.meta_key = 'region' AND wpostmeta2.meta_value  = '".$_POST['search-location']."')"; 
} 
    $querystr .= " ORDER BY post_date DESC LIMIT 50"; 

//Execute 
//echo $querystr; 
$pageposts = $wpdb->get_results($wpdb->prepare($querystr, OBJECT)); 

任何幫助將是偉大的!

+3

**警告:** *您的代碼易受SQL注入攻擊!*閱讀[Bobby Tables](http://bobby-tables.com)的故事以獲取更多信息。 – eggyal

+0

我想你使用自定義查詢,而不是WP_Query類。你能確認'wpostmeta'是你餐桌的名字嗎? – pgk

+0

查詢字符串的其餘部分在哪裏?在AND之前你沒有分享這個部分。 – rnevius

回答

0

此代碼在生產WordPress網站中使用非常危險。你需要刪除它和任何其他模板文件用這樣的SQL查詢。

而是使用WP_Query自動清理SQL請求。它有大量的參數可以設置查詢WordPress的任何內容。以下是使用WP_Query獲取給定分類的帖子的示例,其中tax_query

<?php 
// 1- Setup an argument to give to WP_Query 
$taxonomy_args = array(
    // 2- use the tax_query to examine a taxonomy 
    'tax_query' => array(
    array(
     'taxonomy' => 'job_cat', 
     'terms' => 'XYZ', 
     'field' => 'slug', 
     'include_children' => true, 
     'operator' => 'IN' 
    ) 
), 
    // 3- Make sure to define how many posts and what post-type they should be 
    'posts_per_page' => 50, 
    'post_type' => 'search-location', 
); 

$s = new WP_Query($some_args); 

if ($s->have_posts()) : $s->the_post(); 
    // 4- Here you will manipulate the data you get back 
endif; 
?>