Assign Tags To Posts from Tag Edit Screen
This PHP code integrates with WordPress and Advanced Custom Fields (ACF) to enhance tag management by allowing users to directly associate specific posts with a tag from within the tag's edit screen in the WordPress admin. When editing an individual tag, a custom field titled "Select Posts" is displayed, where users can select one or more posts to be tagged. Upon saving the tag, the selected posts are automatically assigned to that tag, streamlining the process of organizing content by tags. This functionality is especially useful for site administrators and content managers looking to efficiently manage and categorize posts within their WordPress site.
<?php /** * Conditional display of ACF field based on the current URL. */ function cwpai_conditional_acf_field_display($field) { // Get the current URL $current_url = $_SERVER['REQUEST_URI']; // Check if the URL is for the 'Add New Tag' screen or the tag listing page if (strpos($current_url, '/wp-admin/edit-tags.php?taxonomy=post_tag') !== false) { // Further check if it's not an individual tag edit screen if (strpos($current_url, '&tag_ID=') === false) { // If we are on the 'Add New Tag' or tag listing page, return false to hide the field return false; } } // If conditions are not met, show the field normally return $field; } add_filter('acf/prepare_field/key=field_1', 'cwpai_conditional_acf_field_display'); /** * Use ACF to create a custom field in the tag edit form for selecting posts. * (No changes needed here, provided for context) */ function cwpai_add_acf_to_tags() { if(function_exists('acf_add_local_field_group')): acf_add_local_field_group(array( 'key' => 'group_1', 'title' => 'Post Selector', 'fields' => array( array( 'key' => 'field_1', 'label' => 'Select Posts', 'name' => 'select_posts', 'type' => 'post_object', 'post_type' => array('post'), 'multiple' => 1, 'return_format' => 'id', ), ), 'location' => array( array( array( 'param' => 'taxonomy', 'operator' => '==', 'value' => 'post_tag', ), ), ), )); endif; } add_action('acf/init', 'cwpai_add_acf_to_tags'); /** * Save selected posts to the tag when the tag is edited. * (No changes needed here, provided for context) */ function cwpai_save_tag($term_id) { if (isset($_POST['acf'])) { $selected_posts = $_POST['acf']['field_1']; // Ensure this matches the actual field key used in $_POST data if (!empty($selected_posts)) { foreach ($selected_posts as $post_id) { wp_set_post_terms($post_id, array($term_id), 'post_tag', true); } } } } add_action('edited_term', 'cwpai_save_tag');
Frequently Asked Questions
It checks the current URL and hides the ACF field on the 'Add New Tag' or tag listing page unless editing a specific tag.