doumaojin4008 2011-02-22 00:11
浏览 117
已采纳

WordPress PHP - 如何按特定的“meta_key”值对类别/归档结果进行排序?

I previously made a post here: How do I sort by a custom field without manually creating a new page?

However, I believe I asked the wrong question (and I may still be asking the wrong question). Actually think I may need a complex query that will display posts ordered by a meta value. The site is using a theme called "AgentPress". I believe passing params via the URL bar may be too simplistic for what I need.

Honestly I like the way the current category pages display (formatting, etc.), I simply need to "short-circuit" the process so that any category/archive page is sorted by the meta_key for the "property price" as opposed to the date of entry. If there is a simple, more "WordPress-y" mechanism for doing this, I'm all ears. Please be explicit about where to place the code, etc.

FYI, at this point it's clear that passing "order=ASC" and "order=DESC" in the URL works. However, it seems that nothing I do with "meta_key" or anything related has any effect.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • douxiaqin2062 2011-03-02 20:17
    关注

    You can add a filter on pre_get_posts hook.

    Put this code in functions.php (in your theme dir) :

    add_filter('pre_get_posts', 'pre_get_posts_hook' );
    
    function pre_get_posts_hook($wp_query) {
        if (is_category() || is_archive())
        {
            $wp_query->set( 'orderby', 'meta_value_num' );
            $wp_query->set( 'meta_key', 'price' );
            $wp_query->set( 'order', 'ASC' );
            return $wp_query;
        }
    }
    

    You can use meta_value instead of meta_value_num (available with v2.8), but I assume that price is a numeric value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用