简体   繁体   English

按自定义字段对自定义帖子类型进行排序

[英]Sort Custom Post Type by Custom Field

How can you sort a custom post type by a custom field in Wordpress? 如何通过Wordpress中的自定义字段对自定义帖子类型进行排序? I'm trying to figure out a way to echo a custom field called 'State' alphabetically and place the custom post type links called employees under each of their respect states. 我试图找出一种方法来按字母顺序回显一个名为“州”的自定义字段,并将名为雇员的自定义帖子类型链接放在每个尊重状态下。

So it would look like this: 所以它看起来像这样:

Alabama 阿拉巴马州

  • Appleseed, Johnny 苹果种子,约翰尼
  • Chamber, Pete 皮特·钱伯

Florida 佛罗里达

  • Miller, Sam 米勒,山姆
  • Stark, Amy 艾米·史塔克

    I know how to write the basic loop for a custom post type but I'm not sure how to sort under a custom field belonging to that post type alphabetically. 我知道如何为自定义帖子类型编写基本循环,但是我不确定如何按字母顺序在属于该帖子类型的自定义字段下进行排序。

     <?php $query = new WP_query ( array( 'post_type'=> 'employees', 'meta_key'=> 'state', 'orderby'=> 'meta_value', 'order' => 'DESC')); while ( $query -> have_posts() ) : $query -> the_post(); ?> <?php echo get_post_meta($post->ID, 'state', true); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php endwhile; wp_reset_query(); ?> 

You could do something like this: 您可以执行以下操作:

<?php $query = new WP_query ( array( 'post_type'=> 'employees', 'meta_key'=> 'state', 'orderby'=> 'meta_value', 'order' => 'DESC'));
  while ( $query -> have_posts() ) : $query -> the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
  <?php
endwhile;   
wp_reset_query();  ?>

Finally got it thanks to this link: http://pastebin.com/b4WGrMhD 终于有了这个链接: http : //pastebin.com/b4WGrMhD

<?php $employeesQuery = new WP_Query(array('post_type' => 'employees', 'meta_key' => 'state', 'orderby' => 'meta_value', 'order' => 'ASC', 'posts_per_page' => '-1')); ?>
  <?php $prevltr = ""; ?>
    <?php if(have_posts()) { while ( $employeesQuery->have_posts() ) { $employeesQuery->the_post(); ?>
            <?php $state = get_post_meta($post->ID, 'state', true); ?>
            <?php $curltr = $state; ?>
            <?php if($curltr != $prevltr) : ?>
                <a name="section-<?php echo $curltr ?>"></a><br class="clear" /><h4><?php echo $curltr; $prevltr = $curltr; ?></h4>
            <?php endif; ?>

            <article class="employee-entry" id="entry-<?php the_title_attribute(); ?>">

                <div><strong><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></strong></div>
                <div><?php $terms = get_the_terms( $post->ID , 'titles' ); foreach( $terms as $term ) { print $term->name; unset($term); } ?></div>

            </article>

<?php }} ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM