在后台发布文章时,如果我们想它默认就选中了某个分类,方法有很多,比如通过js来执行,或者通过GET方式传值来默认选中,下面模板兔提供下如何通过GET传值方式来默认选分类。例如:wp-admin/post-new.php?cat=news
add_action( 'new_to_auto-draft', function( $post ) {
// Bail out, if not in admin editor.
if ( ! strpos( $_SERVER['REQUEST_URI'], 'wp-admin/post-new.php' ) ) {
return;
}
// Bail out, it no category set in $_GET.
if ( empty( $_GET['cat'] ) ) {
return;
}
$cat = wp_unslash( $_GET['cat'] );
// Bail out, if category does not exist.
if ( false === ( $cat = get_category_by_slug( $cat ) ) ) {
return;
}
wp_set_post_categories( $post->ID, array( $cat->term_id ) );
} );


1 个评论