2013-04-12 37 views
1

我正在開發一個Wordpress插件,需要使用我的插件創建的自定義表格來訂購站點的帖子。wordpress posts_orderby過濾器插件中的自定義表格

我不想更改主題內的代碼,所以我在代碼上找到了過濾器posts_orderbyposts_join(在這裏找到:https://codex.wordpress.org/Custom_Queries)。

自定義表具有以下值:

ID slug price 

,並在我加入這行的插件文件:

add_filter('posts_orderby','custom_orderby'); 
add_filter('posts_join','custom_join'); 

function custom_join($join){ 
    global $wpdb; 
    $customTable = $wpdb->prefix.'custom_table'; 

    if(!is_admin()){ 
     $join .= " LEFT JOIN $customTable ON $wpdb->postmeta.meta_value = $customTable.slug"; 
    } 
    return $join; 
} 
function custom_orderby($orderby_statement){ 
    global $wpdb; 
    $customTable = $wpdb->prefix.'custom_table'; 

    if(!is_admin()){ 
     $orderby_statement = "$customTable.price DESC"; 
    } 
    return $orderby_statement; 
} 

當我刷新索引頁它給了我此錯誤消息:

No Results Found 

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post. 

我試圖用這段代碼直接在我的數據庫上執行查詢:

SELECT * FROM wp_posts t1 
    LEFT JOIN wp_postmeta t2 ON t1.ID = t2.post_id 
    LEFT JOIN wp_custom_table t3 ON t2.meta_value = t3.slug 

ORDER BY t3.price DESC 

它工作。

所以在我的插件文件中寫入的代碼有問題,但我無法弄清楚。

+0

好吧,我部分解決了我的問題。 我在'custom_join()'函數中添加了另一行代碼。 現在的代碼是這樣的: function custom_join($ join){} – DanieleBiggiogero

+0

好的我對評論弄得一團糟。代碼是這樣的: 好的,我部分解決了我的問題。 我在'custom_join()'函數中添加了另一行代碼。 現在的代碼是這樣的: function custom_join($ join){ global $ wpdb; $ customTable = $ wpdb-> prefix.'custom_table'; (!is_admin()){ $ join。=「LEFT JOIN wp_postmeta t1 ON wp_posts.ID = t1.post_id」; $ join。=「LEFT JOIN $ customTable t2 ON t1.meta_value = t2.slug」; } return $ join; } 它的工作原理,但有一些其他問題。 現在我看到一些重複的帖子。 – DanieleBiggiogero

回答

4

好的,我解決了它。

的問題是,後查詢不包括postmeta表,所以我加了它的custom_join功能,像這樣:

add_filter('posts_join','custom_join'); 
add_filter('posts_orderby','custom_orderby'); 

function custom_join($join){ 
    global $wpdb; 
    $customTable = $wpdb->prefix."custom_table"; 

    if(!is_admin){ 
     $join .= "LEFT JOIN $wpdb->postmeta p1 ON $wpdb->posts.ID = p1.post_id"; 
     $join .= "LEFT JOIN $customTable p2 ON p1.meta_value = p2.slug"; 
    } 

    return $join; 
} 

function custom_orderby($orderby_statement){ 
    global $wpdb; 

    if(!is_admin){ 
     $orderby_statement = "p2.price DESC, $wpdb->posts.post_date DESC"; 
    } 

    return $orderby_statement; 
} 

我還添加了posts_groupby濾波器,因爲新的查詢給了我重複的帖子(大量重複的帖子)。

下面的代碼:

add_filter('posts_groupby','custom_groupby'); 

function custom_groupby($groupby){ 
    global $wpdb; 

    if(!is_admin){ 
     $groupby = "$wpdb->posts.ID"; 
    } 

    return $groupby; 
} 

一切都寫在插件文件,但你也可以寫在function.php文件的主題。

如果您想在前端看到自定義查詢只有,請記住包含if(!is_admin)聲明。