这是一个常见的问题,我一直无法找到一个简单的答案。
我想生成一个自定义帖子类型标题的列表。我'orderby' => 'title'
用来让他们按字母顺序显示。标题是名字和姓氏,我想按姓氏排序。我知道我可以用姓和名分开创建元字段和按姓字段的顺序。但我真的很想看看有没有好办法explode
的'title'
,并传递到'排序依据”的第二个字。
这是基本代码:
<?php
// Get the 'Actors' post type
$args = array(
'post_type' => 'actors',
'orderby' => 'title',
'order' => 'ASC',
'nopaging' => true,
'cache_results' => false,
'update_post_meta_cache' => false
);
$loop = new WP_Query($args);
while($loop->have_posts()): $loop->the_post();
echo '<li><img src="' . get_post_meta(get_the_ID(),'_dtm_small_image', [0]) . '"><span>' . get_the_title() . '</span></li>';
endwhile;
wp_reset_query();
?>
我试图:
$gettitle = get_the_title();
$lastname = explode(" ", $gettitle);
然后更改为'orderby' => $lastname[1],
。但它不起作用。
有没有好的方法可以使用标题中的第二个单词对帖子进行排序?
您无法通过循环执行此操作,WordPress没有选择。
您可以做的就是拆分标题并创建一个数组:
$people = array();
while($loop->have_posts()): $loop->the_post();
list($firstname, $lastname) = explode(" ", get_the_title() ); // You can use list, since you said that's you only first and last name on the title.
$people[] = $lastname;
endwhile;
wp_reset_query();
sort($people); // Sort the array Asc. NOTE: You can create a function to sort by sort or rsort, on input
foreach ($people as $last) {
echo $last, "<br />"; // echo the last name
}
这不是很有效,但是可以。您应该考虑将两个字段添加到WordPress。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句