我試圖在functions.php
內部創建一個函數,以用來自幾個自定義字段的信息替換自定義帖子標題。在發佈帖子之前,我想評估它是否已經創建,或者這是否是新帖子;如果它是一個新帖子,我想從幾個字段獲取信息,請計算此自定義帖子類型中的帖子總數並創建標題;如果這只是編輯已有的帖子,我想使用$_POST['post_title']
字段中的內容。創建函數來替換帖子標題不起作用
function custom_field_value_as_title($value, $post_id, $field) {
global $_POST;
// vars
$title = $_POST['post_title'];
$post = get_page_by_title($title, 'OBJECT', 'mascotas');
if (FALSE === get_post_status($post_id)) {
$new_title_ciudad = get_field('ciudad', $post_id);
$new_title_sexo = get_field('sexo', $post_id);
$new_title_especie = get_field('especie' , $post_id);
$registered_year = date("y");
$count_mascotas = wp_count_posts('mascotas');
$next_count = $count_mascotas->publish + 1;
$new_count = sprintf("%04d", $next_count);
$new_title = "$new_title_ciudad"."$new_title_sexo"."$new_title_especie"."$registered_year"."-"."$new_count";
// update post
$my_post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $post_id
);
// Update the post into the database
wp_update_post($my_post);
} else {
// vars
$new_title = $_POST['post_title'];
// update post
$my_post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $post_id
);
// Update the post into the database
wp_update_post($my_post);
}
}
add_filter('acf/update_value', 'custom_field_value_as_title', 10, 3);
它對已經創建的帖子有效,但它沒有運行創建自定義帖子標題的函數部分。有什麼建議麼?提前致謝!
我代替我的功能與一個KSNO建議:
<?php
function title_replace_function($post_id, $post) {
if ($post->post_date == $post->post_modified) {
global $_POST;
$new_title_ciudad = get_field('ciudad', $post_id);
$new_title_sexo = get_field('sexo', $post_id);
$new_title_especie = get_field('especie' , $post_id);
$registered_year = date("y");
$count_mascotas = wp_count_posts('mascotas');
$next_count = $count_mascotas->publish + 1;
$new_count = sprintf("%04d", $next_count);
$new_title = "$new_title_ciudad"."$new_title_sexo"."$new_title_especie"."$registered_year"."-"."$new_count";
// update post
$my_post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $post_id
);
// Update the post into the database
wp_update_post($my_post);
} else {
// vars
$new_title = $_POST['post_title'];
// update post
// http://codex.wordpress.org/Function_Reference/wp_update_post
$my_post = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $post_id
);
// Update the post into the database
wp_update_post($my_post);
}
}
add_action('publish_post', 'title_replace_function', 10, 2);
?>
當判斷,如果該職位是不是「新的」它正常工作。但它沒有獲得自定義字段值來爲新帖子創建新標題。標題字段爲空。我甚至嘗試將一個自定義字段的值添加到'$ new_title'變量,並且沒有任何內容
檢查編輯答案 – ksno