最简单的方法是添加一个过滤器(在主题的“functions.php”中)按内容排序:
function wpse181797_posts_orderby( $orderby, $query ) {
if ( ! is_admin() && $query->get( \'post_type\' ) == \'post\' /* && some other conditions probably... */ ) {
global $wpdb;
$pc = \'LTRIM(\' . $wpdb->posts . \'.post_content)\';
$orderby = \'UPPER(\' . $pc . \') ASC\';
}
return $orderby;
}
add_filter( \'posts_orderby\', \'wpse181797_posts_orderby\', 10, 2 );
然而,这不会处理任何初始标点符号或HTML标记或诗句编号/标题/题词或其他任何内容,因此对于这些情况,您可能最好也使用辅助字段,例如
post_excerpt
如果可用,则在例外情况下,将第一行按需要排序,因此过滤器变为:
function wpse181797_posts_orderby_excerpt( $orderby, $query ) {
if ( ! is_admin() && $query->get( \'post_type\' ) == \'post\' /* && some other conditions probably... */ ) {
global $wpdb;
$pc = \'LTRIM(CONCAT(\' . $wpdb->posts . \'.post_excerpt, \' . $wpdb->posts . \'.post_content))\';
$orderby = \'UPPER(\' . $pc . \') ASC\';
}
return $orderby;
}
add_filter( \'posts_orderby\', \'wpse181797_posts_orderby_excerpt\', 10, 2 );
如果您使用
post_excerpt
出于其他目的,您可以使用自定义字段,例如
\'first_line_sort\'
, 然后打开过滤器
posts_clauses
(要添加联接):
function wpse181797_posts_clauses( $pieces, $query ) {
if ( ! is_admin() && $query->get( \'post_type\' ) == \'post\' /* && some other conditions probably... */ ) {
global $wpdb;
$pieces[ \'join\' ] .= $wpdb->prepare(
\' LEFT JOIN \' . $wpdb->postmeta . \' wpse_pm ON wpse_pm.post_id = \' . $wpdb->posts . \'.ID\'
. \' AND wpse_pm.meta_key = %s\'
, \'first_line_sort\'
);
$pieces[ \'orderby\' ] = \'UPPER(LTRIM(IFNULL(wpse_pm.meta_value, \' . $wpdb->posts . \'.post_content))) ASC\';
}
return $pieces;
}
add_filter( \'posts_clauses\', \'wpse181797_posts_clauses\', 10, 2 );