Назначьте пользовательские таксономии пользовательской публикации при ее создании в зависимости от параметров, выбранныхPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Назначьте пользовательские таксономии пользовательской публикации при ее создании в зависимости от параметров, выбранных

Сообщение Anonymous »

Я использую ACF для создания новых пользовательских сообщений на основе отправки формы, созданной WP User Frontend.
Он генерирует сообщение и заполняет поля, как предполагалось, но в форме есть 8 различных переключателей с По 2 значения в каждом, чтобы пользователь мог выбирать услуги, которые предлагает его бизнес.
Мне нужно назначить пользовательские таксономии для сообщения в зависимости от значений, которые они выбрали в каждом, а также обновить их, если пользователь редактирует их варианты позже.
Вот код, который я пробовал, но безрезультатно:

Код: Выделить всё

    // Check if it's a custom post type
if (get_post_type($post_id) != 'business-user') { // Change 'business-user' to your actual custom post type if different
return;
}

// Define the terms for each radio option and its selections
$options_terms = array(
'service_1' => array( // Change 'service_1' to your actual ACF option field name
'Service One' => 'Service One', // Change 'Service One' to the actual value and term you want
'No' => 'No', // Change 'No' to the actual value and term you want
),
'service_2' => array( // Change 'service_2' to your actual ACF option field name
'Service Two' => 'Service Two', // Change 'Service Two' to the actual value and term you want
'No' => 'No', // Change 'No' to the actual value and term you want
),
// Continue for other option fields
'service_3' => array(
'Service Three' => 'Service Three',
'No' => 'No',
),
'service_4' => array(
'Service Four' => 'Service Four',
'No' => 'No',
),
'service_5' => array(
'Service Five' => 'Service Five',
'No' => 'No',
),
'service_6' => array(
'Service Six' => 'Service Six',
'No' => 'No',
),
'service_7' => array(
'Service Seven' => 'Service Seven',
'No' => 'No',
),
'service_8' => array(
'Service Eight' => 'Service Eight',
'No' => 'No',
),
);

$terms_to_assign = array();

// Iterate through each option field
foreach ($options_terms as $option_field => $selections) {
// Get the value of the current option field
$option_value = get_field($option_field, 'option'); // Ensure 'option' is used for ACF options page fields

// Check if the option value exists in the selections array
if (array_key_exists($option_value, $selections)) {
// Add the corresponding term to the list of terms to assign
$terms_to_assign[] = $selections[$option_value];
}
}

if (!empty($terms_to_assign)) {
// Assign the collected terms to the post in the custom taxonomy
wp_set_object_terms($post_id, $terms_to_assign, 'service', true); // Change 'your_custom_taxonomy' to your actual custom taxonomy
}
}

add_action('save_post', 'assign_terms_based_on_acf_options');

function update_terms_on_acf_options_change($value, $post_id, $field) {
// List of your option fields
$option_fields = array(
'service_1', // Change these to your actual ACF option field names
'service_2',
'service_3',
'service_4',
'service_5',
'service_6',
'service_7',
'service_8'
);

// Ensure it's one of the option fields
if (in_array($field['name'], $option_fields)) {
$args = array(
'post_type' => 'business-user', // Change 'business-user' to your actual custom post type
'posts_per_page' => -1,
);

$posts = get_posts($args);

foreach ($posts as $post) {
// Update terms for each post
assign_terms_based_on_acf_options($post->ID);
}
}
return $value;
}

add_filter('acf/update_value', 'update_terms_on_acf_options_change', 10, 3);

Будем благодарны за любую помощь.

Подробнее здесь: https://stackoverflow.com/questions/786 ... on-the-opt
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»