Hello dear developers!

Put WP 5.0.3. I use ACF and WPML plugins. Bilingual website

Using the ACF module, added the slug field, which should be unique to post_id. In the settings of the field there is no such functionality. googled, as far as possible came to the conclusion that you should write the test yourself.

As a result, I wrote this code and added it to the theme's functions.php file.

add_filter('acf/validate_value/name=slug', 'slug_validate_value', 10, 4); add_filter( 'wp_insert_post_data', 'create_directories_by_slug', 10, 2 ); function check_existing_slug($slug){ global $wpdb; $post_id = get_the_ID(); $sql = " SELECT 1 FROM $wpdb->postmeta pm LEFT JOIN $wpdb->posts p ON pm.post_id = p.id WHERE pm.meta_key = 'slug' AND pm.meta_value = '{$slug}' AND p.post_parent != $post_id GROUP BY p.post_parent "; $posts_terms = $wpdb->get_results($sql, ARRAY_A); $count = $wpdb->num_rows; return $count; } function slug_validate_value( $valid, $value, $field, $input ){ if( !$valid ) { return $valid; } $check_slug = check_existing_slug($value); if ($check_slug) { $valid = '123'; } return $valid; } function slug_replace($slug) { $pattern = '#[^0-9\\p{L}]+#ui'; $replacement = '-'; $slug = preg_replace($pattern, $replacement, trim($slug)); $slug = strtolower($slug); return $slug; } function create_directory_by_slug($slug) { $uploads_dir = ABSPATH . '/uploads/'; $dir_name = $uploads_dir . $slug; $languages = wpm_get_languages(); $folders = [ 'description', 'presentation', 'best_practices', 'faces_stories', 'videos', 'photos', 'reports', 'additional_materials' ]; if(!is_dir($dir_name)) { mkdir($dir_name); foreach ($languages as $code => $language) { !is_dir($dir_name . '/' . $code) && mkdir($dir_name . '/' . $code); foreach ($folders as $folder) { !is_dir($dir_name . '/' . $code . '/' . $folder) && mkdir($dir_name . '/' . $code . '/' . $folder); } } return true; } } 

What did I want to get in the end?

I wanted: if the user fills in the slug field that already exists in the database, then I would get an error message that it should be at the local level and as a result, the script would not create the necessary folders for me.

Tell me if I think correctly, and if not, then which way to dig.

Thank you all in advance!

  • Please change the question title to something sane. - KAGG Design

0