0

請問如何根據ACF中的字段(參見圖片)對我的產品(這是我的自定義帖子類型)進行排序?排序我的自定義文章中的產品中的ACF字段在Wordpress中

enter image description here

這裏是我的自定義字段代碼:

/*******   *******/ 
/* CUSTOM POST TYPE  */ 
/*******   *******/ 

// Custom Post Type - product 
function register_post_product() { 
    $labels = array(
    'name'    => __('Products', '_tk'), 
    'singular_name'  => __('Product', '_tk'), 
    'add_new'   => __('Add product', '_tk'), 
    'add_new_item'  => __('Add New product', '_tk'), 
    'edit_item'   => __('Edit product', '_tk'), 
    'new_item'   => __('New product', '_tk'), 
    'all_items'   => __('All products', '_tk'), 
    'view_item'   => __('View product', '_tk'), 
    'search_items'  => __('Search product', '_tk'), 
    'not_found'   => __('No product found', '_tk'), 
    'not_found_in_trash' => __('No product found in the Trash', '_tk'), 
    'parent_item_colon' => '', 
    'menu_name'   => __('Products', '_tk'), 
); 
    $args = array(
    'labels'   => $labels, 
    'hierarchical'  => true, 
    'supports'   => array('title', 'editor', 'page-attributes', 'thumbnail'), 
    'public'   => true, 
    'show_ui'   => true, 
    'show_in_menu'  => true, 
    'show_in_nav_menus' => true, 
    'publicly_queryable' => true, 
    'exclude_from_search' => false, 
    'has_archive'  => true, 
    'rewrite'   => array('slug' => 'produkty','with_front' => false), 
    'menu_position'  => 6, 
    'menu_icon'   => 'dashicons-hammer' 
); 
    register_post_type('product', $args); 
} 
add_action('init', 'register_post_product'); 

我做在谷歌一些搜索,我想這樣的排序是:

add_filter('pre_get_posts', 'my_get_posts'); 
function my_get_posts($query) { 
     $query->set('orderby', 'meta_value_num'); 
     $query->set('order', 'ASC'); 
     $query->set('meta_query','capacity'); 

     return $query; 
} 

,但沒有結果。

回答

0

在WordPress

<?php 
add_filter('pre_get_posts', 'my_get_posts'); 
function my_get_posts($query) { 

    $query->set('post_type', 'product'); 
    $query->set('meta_key', 'capacity'); 
    $query->set('orderby', 'meta_value'); // meta_value_num or meta_value 
    $query->set('order', 'ASC'); 


    return $query; 
} 
?> 
試試這個下面功能pre_get_posts
+0

不幸的是我重新擁有空白包sult –

0

最有可能的問題是$query->set('meta_query','capacity');

meta_query應該是一個數組,像

array(array('key' => 'capacity', 
      'value' => array(0, 1000), 
      'compare' => 'BETWEEN', 
      'type' => 'numeric', 
    )); 

https://codex.wordpress.org/Class_Reference/WP_Query

+0

我不知道我是否正確輸入了它? 'add_filter('pre_get_posts','my_get_posts'); function my_get_posts($ query){ \t $ query-> set('orderby','meta_value_num'); \t $ query-> set('order','ASC'); \t $查詢 - >置( 'meta_query',陣列( '鍵'=> '能力', '值'=>數組(0,10000), '比較'=> '之間', )) ; \t \t return $ query; }「 因爲沒有工作:( –

+0

您的代碼似乎是正確的,這是我的不好,我更新了答案的代碼,meta_queries嵌套數組。但@清淳,marakana的解決方案,甚至更好,應該工作以及。如果WP_DEBUG在wp-config.php中被禁用,你可能會得到一個空白頁面 – c0der

+0

@Shital-Marakana的解決方案仍然有問題,我評論了兩行: '$ query-> set(' ('meta_key','capacity');' 和現在的產品出現但仍然未排序。任何想法可能是錯誤的? –

相關問題