钩住save_post
只适用于新职位。它不会解决现有员额的问题。这只能用钩子解决init
甚至更好admin_init
并在选项表中标记它,以防止它在每个后续请求上执行。
此外,对于新职位来说,更有效的方法是save_post_{$post_type}
,
//for existing posts...
add_action(\'admin_init\', \'udpate_crosses_once`);
function udpate_crosses_once(){
$flag = get_option(\'crosses_updated\', \'no\');
if(\'no\'===$flag){
$args = array(
\'post_type\' => \'crosses\',
\'post_status\' => \'publish\',
\'posts_per_page\' => -1
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
$length = strlen( trim( $post->post_title ) );
update_post_meta( $post->ID, \'name_length_crosses\', $length );
}
add_option(\'crosses_updated\', \'yes\'); //set flag.
}
}
//for new posts...
add_action( \'save_post_crosses\', \'save_crosses_title_length\', 10, 2 );
function save_crosses_title_length( $post_id, $post) {
// Check to see if we are autosaving
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE){
return;
}
$length = strlen( trim($post->post_title) );// get the length of title
//udpate the meta field, in case the post title is being updated
update_post_meta( $post_id, \'name_length_crosses\', $length );
//note, no need to add_post_meta, udpate_post_meta fn will add the field if not found.
}
对于前端显示器,
$crossposts = get_posts(array(
\'post_type\' => \'crosses\',
\'meta_key\' => \'name_length_crosses\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\'
));
if ( $crossposts ) {
foreach ( $crossposts as $post ) :
setup_postdata( $crossposts ); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
<?php
endforeach;
wp_reset_postdata(); //Important, reset the query post data.
}