我使用的是高级自定义字段,我有一个名为“recipe”的自定义帖子类型。
我使用以下代码根据名为recipe\\u name的自定义字段设置自定义帖子标题:
function my_post_title_updater( $post_id ) {
$my_post = array();
$my_post[\'ID\'] = $post_id;
$recipe_name = get_field(\'recipe_name\');
if ( get_post_type() == \'recipe\' ) {
$my_post[\'post_title\'] = get_field(\'recipe_name\');
}
// Update the post into the database
wp_update_post( $my_post );
}
// run after ACF saves the $_POST[\'fields\'] data
add_action(\'acf/save_post\', \'my_post_title_updater\', 20);
上述代码非常有效。。但我也在尝试另外如何运行下面的函数,但我根本看不到我的post Slug得到更新。它们保存为“auto-draft-4”,并从那里开始递增。
function slug_save_post_callback( $post_ID, $post, $update ) {
// allow \'publish\', \'draft\', \'future\'
if ($post->post_type != \'recipe\' || $post->post_status == \'auto-draft\')
return;
// only change slug when the post is created (both dates are equal)
if ($post->post_date_gmt != $post->post_modified_gmt)
return;
// use title, since $post->post_name might have unique numbers added
$new_slug = sanitize_title( $post->post_title, $post_ID );
$subtitle = sanitize_title( get_field( \'subtitle\', $post_ID ), \'\' );
if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
return; // No subtitle or already in slug
$new_slug .= \'-\' . $subtitle;
if ($new_slug == $post->post_name)
return; // already set
// unhook this function to prevent infinite looping
remove_action( \'acf/save_post\', \'slug_save_post_callback\', 21, 3 );
// update the post slug (WP handles unique post slug)
wp_update_post( array(
\'ID\' => $post_ID,
\'post_name\' => $new_slug
));
// re-hook this function
add_action( \'acf/save_post\', \'slug_save_post_callback\', 21, 3 );
}
add_action( \'acf/save_post\', \'slug_save_post_callback\', 21, 3 );
SO网友:damrakred
我发现一些代码允许从自定义字段数据生成帖子标题和Slug:
function recipe_update_title( $value, $post_id, $field ) {
$new_title = get_field( \'recipe_name\', $post_id) . \' \' . $value;
$new_slug = sanitize_title( $new_title );
// update post
$recipe_postdata = array(
\'ID\' => $post_id,
\'post_title\' => $new_title,
\'post_name\' => $new_slug,
);
if ( ! wp_is_post_revision( $post_id ) ){
// unhook this function so it doesn\'t loop infinitely
remove_action(\'save_post\', \'recipe_update_title\');
// update the post, which calls save_post again
wp_update_post( $recipe_postdata );
// re-hook this function
add_action(\'save_post\', \'recipe_update_title\');
}
return $value;
}
add_filter(\'acf/update_value/name=recipe_featured_image\', \'recipe_update_title\', 10, 3);