我想用ACF前端形式函數來創建帶定製字段的形式ACF前端的形式更新項
我看到這個問題了創建新名詞,@Alhana ACF front end form to create term 但我想生成表單與舊數據
我想用ACF前端形式函數來創建帶定製字段的形式ACF前端的形式更新項
我看到這個問題了創建新名詞,@Alhana ACF front end form to create term 但我想生成表單與舊數據
嗯,我沒有看到這個問題,但如果它仍然是實際的,這是一個解決方案。 首先,確保你有ACF組,鏈接到你的分類。您需要ID這組,它可以在URL組編輯頁面上找到,例如:
http://site.ru/wp-admin/post.php?post=340&action=edit
在這種情況下,組ID 。如果你不希望使用硬編碼ID(如果你的組不時改變),你可以得到它,使用組名(在這個例子中的組名是TECHNIC CPT):
global $wpdb;
$group_ID = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'");
然後,您需要您正在更新的術語ID。我認爲,這不是nesessary寫得到它,因爲它是WP基礎:)你會用這樣的結尾:
$term_id = 405;
最後,你需要你的分類的蛞蝓。在這個例子中,它是技術。所以,讓我們渲染我們的表單!
acf_form_head();
$acf_form_args = array(
'id' => 'technic_edit_form',
'post_id' => 'technic_'.$term_id,
'form' => true,
'submit_value' => 'Update technic',
'field_groups' => array($group_ID),
'updated_message' => 'Technic is updated!';
);
acf_form($acf_form_args);
現在您的術語的自定義字段將以此格式顯示。但爲了在編輯後保存術語數據,您需要添加更多代碼。 ACF表格假定您正在保存發佈數據,我們將添加一些邏輯來檢測爲術語保存數據。
add_filter('acf/pre_save_post', 'acf_handle_form_save', 10, 1);
function acf_handle_form_save($post_id) {
// Function accepts id of object we're saving.
// All WordPress IDs are unique so we can use this to check which object it is now.
// We'll try to get term by id.
// We'll get term id with added taxonomy slug, for example 'technic_405'.
// For checking term existence we must cut out this slug.
$cut_post_id = str_replace('technic_', '', $post_id);
$test_tax_term = get_term_by('id', $cut_post_id, 'technic');
// If $test_tax_term is true - we are saving taxonomy term.
// So let's change form behaviour to saving term instead of post.
if ($test_tax_term) :
// Get array of fields, attached to our taxonomy
global $wpdb;
$group_ID = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = 'Technic CPT'");
$acf_fields = acf_get_fields_by_id($group_ID);
// Then sanitize fields from $_POST
// All acf fields will be in $_POST['acf']
foreach ($acf_fields as $acf_field) :
$$acf_field[ 'name' ] = trim(esc_attr(strip_tags($_POST[ 'acf' ][ $acf_field[ 'key' ] ])));
endforeach;
// We need to have some fields in our group, which are just duplicates of standard term fields: name, slug, description.
// In this example it's only one field - term name, called 'technic_name'.
$name = 'technic_name';
// Update base term info, in this example - only name.
$term = wp_update_term($cut_post_id, 'technic', array('name' => $$name));
// If all is correct, update custom fields:
if (!is_wp_error($term)) :
foreach ($acf_fields as $acf_field) :
update_field($acf_field[ 'name' ], $$acf_field[ 'name' ], 'technic_' . $cut_post_id);
endforeach;
endif;
else :
// Here is saving usual post data. Do what you need for saving it or just skip this point
endif;
return $post_id;
}
請注意:$ _ POST數據驗證可能會更復雜。例如,如果在分類法字段之間存在ACF圖庫或關係,則可能必須驗證值的數組。在我的例子中,我只有普通的文本字段。
希望有幫助!