在Wordpress中的自定义帖子类型的产品中按ACF字段排序

时间:2017-07-18 13:25:57

标签: php wordpress sorting custom-post-type advanced-custom-fields

请您告诉我如何在ACF的现场(见图片)对我的产品进行分类(这是我的自定义帖子类型)?

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;
}

但没有结果。

2 个答案:

答案 0 :(得分:0)

在wordpress

中尝试使用以下函数for pre_get_posts
<?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;
}
?>

答案 1 :(得分: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