[英]Wordpress – Sort posts alphabetically by meta value
I have a custom post type of products, and each product belongs to a product category. 我有一个自定义帖子类型的产品,每个产品都属于一个产品类别。 I am trying to query the products to get all products sorted alphabetically by their product category ie
我正在尝试查询产品,以使所有产品均按其产品类别按字母顺序排序,即
First : 首先 :
Product: Lion 产品:狮子
Category: Animals 分类:动物
Last: 持续:
Product: Snowmobile 产品:雪地车
Category: Winter 类别:冬季
I am using a custom field for the product category, but my query doesn't sort them alphabetically - but instead by which date they are published. 我将自定义字段用于产品类别,但是我的查询不是按字母顺序对它们进行排序-而是按发布日期排序。 The product_cat_meta field is a regular text field set up in custom fields.
product_cat_meta字段是在自定义字段中设置的常规文本字段。 Query is here:
查询在这里:
function get_products()
{
$args = array(
'post_type' => 'products',
'post_status' => 'publish',
'meta_key' => 'product_cat_meta',
'orderby' => 'meta_value',
'order' => 'ASC',
'posts_per_page' => -1
);
$products = new WP_Query($args);
if ($products->have_posts()) {
$index = 0;
while ($products->have_posts()) {
$products->the_post();
$prod_meta = get_field('product_cat_meta');
echo $prod_meta;
);
$index++;
} // end while
} // end if
}
The result of this query just returns the prod category in the way they are set up in wordpress – the latest posts first, but not sorted alphabetically 该查询的结果仅以在wordpress中设置的方式返回prod类别-最新帖子优先,但不按字母顺序排序
You can try to put the code in functions.php file. 您可以尝试将代码放在functions.php文件中。
The code, which can be dropped into your current theme's functions.php if you like: 如果愿意,可以将该代码放到当前主题的functions.php中:
function get_products() { $args = array( 'post_type' => 'products', 'post_status' => 'publish', 'meta_key' => 'product_cat_meta', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1 ); $products = new WP_Query($args); if ($products->have_posts()) { $index = 0; while ($products->have_posts()) { $products->the_post(); $prod_meta = get_field('product_cat_meta'); echo $prod_meta; ); $index++; } // end while } // end if }
Get More details, follow the link: https://codex.wordpress.org/Alphabetizing_Posts 获取更多详细信息,请单击链接: https : //codex.wordpress.org/Alphabetizing_Posts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.