【问题标题】:Wordpress orderby second word of meta_valueWordpress orderby meta_value 的第二个单词
【发布时间】:2012-12-13 17:48:27
【问题描述】:

我有一个页面模板“作者”(ID 1814)我用来查询我的帖子(标题:书名和内容:描述),meta_key:author_name,它等于书作者的名字和姓氏_但是,我想仅按作者的姓氏(meta_value 中的第二个单词)对这些帖子进行排序。我可以使用以下方法在循环中过滤获得这些结果:

$values = get_post_custom_values("author_name");
$alpha = end(explode(' ',$values[0]));

但我不知道如何让这些帖子按此结果而不是按作者姓名的名字排序。我在下面找到了 functions.php 文件的查询,我认为它让我走上了正确的道路,但在我使用它时在我的页面上返回了 404 错误。

来自这里的代码:http://randyhoyt.com/wordpress/custom-post-type-ordering/

我什至没有添加要爆炸的 SQL 查询(或者在 SQL 中而不是 PHP 中的任何内容)。不确定该代码是否不起作用,因为我正在查询页面模板而不是 archive.php 文件?有什么建议可以让我走上正确的道路吗?

add_filter('posts_join', 'author_join' );
function author_join($wp_join) {
    if(is_page(1814)) {
        global $wpdb;
        $wp_join .= " LEFT JOIN (
                SELECT post_id, meta_value as author_name
                FROM $wpdb->postmeta
                WHERE meta_key =  'author_name' ) AS DD
                ON $wpdb->posts.ID = DD.post_id ";
    }
    return ($wp_join);
}

add_filter('posts_orderby', 'author_order' );
function author_order( $orderby ) {
    if(is_page(1814)) {
            $orderby = " DD.post_title ASC";
    }
    return $orderby;
}

【问题讨论】:

  • 你是在functions.php文件中还是在其他地方添加了这段代码?

标签: mysql wordpress sql-order-by explode meta-key


【解决方案1】:

我已经处理了一个类似的问题,其中以“The ...”开头的乐队名称在 T 处按字母顺序排列。我实施的修复是颠倒数据库中名称的顺序以满足 MySQL 查询,并且然后显示页面可以使用字符串函数将名称反转回正确的顺序。

显示页面上的类似内容可以修复输出:

// The author's name, reverse ordered.
$author_name = 'Doe,John';

// Break the full name into its parts.
list($last_name,$first_name) = explode(',',$author_name);

// Then display the name in the correct order.
echo(first_name.' '.last_name);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2011-10-11
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多