简体   繁体   中英

Can new posts for custom post types be added last in order?

I've setup a custom post type for creating a Staff directory in Wordpress. When I add a new staff member, they automatically appear first in order of all posts, which makes sense for most kinds of post types.

Using Simple Custom Post Order to rearrange the posts is super easy but it also a hassle to do every time, so I was curious to see if anyone knows if there's a way to automatically add new posts last in order?

Using the very basic code in functions.php to add the post type:

function create_posttype() {

register_post_type( 'staff',

    array(
        'labels' => array(
            'name' => __( 'Staff' ),
            'singular_name' => __( 'Staff' )
        ),
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'staff'),
    )
);
}

add_action( 'init', 'create_posttype' );

There are actually many ways to do this, but here is one:

Add an action to alter the ORDER param in your query as shown below.

add_action('pre_get_posts', function( $query ) {
    $query->set('order', 'ASC');
});

Note that the above query will act on ALL post queries (including in the admin), which is probably not what you want, so you'll have to wrap the $query->set() in logic so it only runs on the page(s) you want. For example, to only change the order when working with the staff CPT, use this:

add_action('pre_get_posts', function( $query ) {
    if ( 'staff' == $query->query['post_type'] ) {
        $query->set('order', 'ASC');
    }
});

Also note that in this action, $query is passed by reference, not by assignment, so there is no need to use the global keyword nor return anything.

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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