Advertisement
Beee

Save field as title

Mar 1st, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.55 KB | None | 0 0
  1.     function sd_set_title_slug_from_headline( $post_id ) {
  2.  
  3.         // bail if no ACF data
  4.         if ( empty( $_POST[ 'acf' ] ) ) {
  5.             // return;
  6.         }
  7.  
  8.         $ad_title = 'field_57e3ed6c92ea0';
  9.         // if sd_ad_title is entered
  10.         if ( ! empty( $_POST[ 'acf' ][ $ad_title ] ) ) {
  11.  
  12.             $entered_title = $_POST[ 'acf' ][ $ad_title ];
  13.             $cleaned_title = preg_replace( '/[^A-Za-z0-9\-\s]/', '', $entered_title ); // Removes special chars.
  14.             $post_name     = sanitize_title( $cleaned_title );
  15.             $city_name     = wp_specialchars_decode( get_field( 'sd_city_search_value', $post_id ), ENT_QUOTES );
  16.             $search_city   = str_replace( '\'', '', $city_name ); // strip '
  17.             $search_city   = str_replace( ' ', '-', $search_city ); // change space
  18.             $new_slug      = strtolower( $search_city ) . '-' . $post_name . '-' . $post_id;
  19.  
  20.             // update acf field
  21.             update_field( 'sd_ad_title', $cleaned_title, $post_id ); // update acf field
  22.  
  23.             // update post status + post title (if needed)
  24.             global $wpdb;
  25.             $wpdb->update(
  26.                 $wpdb->posts,
  27.                 array(
  28.                     'post_title'  => $cleaned_title,
  29.                     'post_name'   => $new_slug
  30.                 ),
  31.                 array(
  32.                     'ID' => $post_id
  33.                 )
  34.             );
  35.  
  36.             clean_post_cache( $post_id );
  37.  
  38.         }
  39.  
  40.     }
  41.     add_action( 'acf/save_post', 'sd_set_title_slug_from_headline', 20 );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement