将此代码添加到functions.php
. 它应该为给定类别的帖子增加元价值
您可以使用硬编码的类别slug/ID,但最好将其存储在options
表,并允许从仪表板进行更改。
将“ID”/“category\\u slug”更改为您自己的。
/**
* @param int $post_ID Post ID.
* @param WP_Post $post_after Post object following the update.
* @param WP_Post $post_before Post object before the update.
*/
function updateNumbers($post_id, $post_after, $post_before) {
global $wpdb;
if ( $post_after->post_type != \'post\' )
return;
$selected_cat_ID = 123; // <-- ID of your category with numbering
// -- select category ID by slug --
// $selected_cat = \'category_slug\';
// $selected_cat_ID = get_terms([\'slug\' => \'category_slug\', \'fields\'=> \'ids\', \'taxonomy\' => \'category\', \'hide_empty\' => false,]);
// if ( !is_array($selected_cat_ID) || empty($selected_cat_ID) )
// return;
// $selected_cat_ID = $selected_cat_ID[0];
// -- end: select category ID by slug --
$incr_number = get_post_meta($post_id, \'incr_number\', true);
//
// get posts assigned to your category
$query = "SELECT p.id FROM {$wpdb->posts} p"
. " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id"
. " LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"
. " LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"
. " WHERE p.post_status = \'publish\' AND p.post_type = \'post\'"
// if you want use slug instead ID change "AND t.term_id = %d" to "AND t.slug = %s"
. " AND tt.taxonomy = \'category\' AND t.term_id = %d"
. " ORDER BY p.post_date ASC";
$ids = $wpdb->get_results( $wpdb->prepare($query, $selected_cat_ID), OBJECT );
// is post assigned to category after update
$in_category = false;
$assigned_posts = [];
foreach( $ids as $row ) {
$assigned_posts[] = $row->id;
if ( $row->id == $post_id )
$in_category = true;
}
if ( !$in_category && $incr_number === \'\' ) {
//
// after the update post is not in the category, before the update was not either
return;
}
else if ($in_category && $incr_number !== \'\' && $post_before->post_date_gmt == $post_after->post_date_gmt ) {
//
// after the update, post is still in the category,
// publish date has not changed,
// numbering doesn\'t need to be changed
return;
}
else if ( !$in_category && $incr_number !== \'\' ) {
//
// post has he been removed from category
delete_post_meta($post_id, \'incr_number\');
}
// update numbering
if ( !empty($assigned_posts) ) {
$counts = 0;
foreach( $assigned_posts as $pid )
update_post_meta($pid, \'incr_number\', ++$counts);
}
}
add_action( \'post_updated\', \'updateNumbers\', 10, 3);