这是一个常见的问题,我无法找到一个直截了当的答案。
我想生成一个自定义帖子类型标题的列表。我使用'orderby' => 'title'
按字母顺序显示它们。标题是名称和姓氏,我想按姓氏排序。我知道我可以使用分隔的名字和姓氏创建元字段,并按姓氏字段排序。但我真的很想看看explode
'title'
是否没有好的方法,并将第二个词传递给`orderby'。
这是基本代码:
<?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],
。但它不起作用。
是否没有好的方法来使用标题中的第二个单词对帖子进行排序?
答案 0 :(得分: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。
答案 1 :(得分:1)
WordPress不允许您按这种方式排序。您必须自己获取帖子并对结果进行排序。我找到了这个答案并且在模拟中正常工作:Sort an array by alphabetically by second word。
模拟:
<?php
function sort_so_10484704($a, $b)
{
list($firstNameA, $lastNameA) = explode(" ", $a["post_title"], 2);
list($firstNameB, $lastNameB) = explode(" ", $b["post_title"], 2);
return strcmp($lastNameA, $lastNameB);
}
$arr = array(
0 => array( 'post_title' => 'Jonh Smith Lorem', 'post_content' => '1st item' ),
1 => array( 'post_title' => 'Abeline Zachs Ipsum', 'post_content' => '2nd item' ),
2 => array( 'post_title' => 'Carlos Xico Non', 'post_content' => '3rd item' ),
3 => array( 'post_title' => 'Kenn Tee Sequitur', 'post_content' => '4th item' )
);
usort($arr, "sort_so_10484704");
printf('<pre>%s</pre>', print_r($arr,true));
结果(S -> T -> X -> Z
):
Array
(
[0] => Array
(
[post_title] => Jonh Smith Lorem
[post_content] => 1st item
)
[1] => Array
(
[post_title] => Kenn Tee Sequitur
[post_content] => 4th item
)
[2] => Array
(
[post_title] => Carlos Xico Non
[post_content] => 3rd item
)
[3] => Array
(
[post_title] => Abeline Zachs Ipsum
[post_content] => 2nd item
)
)
未测试:
$loop = get_posts( $args );
if( $loop ) {
usort($loop, "sort_so_10484704");
foreach( $loop as $post ) {
echo '<li><img src="' . get_post_meta($post->ID,'_dtm_small_image', [0]) . '"><span>' . $post->post_title . '</span></li>';
}
}
检查When should you use WP_Query vs query_posts() vs get_posts()?