Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. function my_post_title_updater( $post_id ) {
  2.  
  3. $my_post = array();
  4. $my_post['ID'] = $post_id;
  5.  
  6. $recipe_name = get_field('recipe_name');
  7.  
  8. if ( get_post_type() == 'recipe' ) {
  9. $my_post['post_title'] = get_field('recipe_name');
  10. }
  11.  
  12. // Update the post into the database
  13. wp_update_post( $my_post );
  14.  
  15. }
  16. // run after ACF saves the $_POST['fields'] data
  17. add_action('acf/save_post', 'my_post_title_updater', 20);
  18.  
  19. function slug_save_post_callback( $post_ID, $post, $update ) {
  20. // allow 'publish', 'draft', 'future'
  21. if ($post->post_type != 'recipe' || $post->post_status == 'auto-draft')
  22. return;
  23.  
  24. // only change slug when the post is created (both dates are equal)
  25. if ($post->post_date_gmt != $post->post_modified_gmt)
  26. return;
  27.  
  28. // use title, since $post->post_name might have unique numbers added
  29. $new_slug = sanitize_title( $post->post_title, $post_ID );
  30. $subtitle = sanitize_title( get_field( 'subtitle', $post_ID ), '' );
  31. if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
  32. return; // No subtitle or already in slug
  33.  
  34. $new_slug .= '-' . $subtitle;
  35. if ($new_slug == $post->post_name)
  36. return; // already set
  37.  
  38. // unhook this function to prevent infinite looping
  39. remove_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );
  40. // update the post slug (WP handles unique post slug)
  41. wp_update_post( array(
  42. 'ID' => $post_ID,
  43. 'post_name' => $new_slug
  44. ));
  45. // re-hook this function
  46. add_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );
  47. }
  48. add_action( 'acf/save_post', 'slug_save_post_callback', 21, 3 );
  49.  
  50. function recipe_update_title( $value, $post_id, $field ) {
  51.  
  52. $new_title = get_field( 'recipe_name', $post_id) . ' ' . $value;
  53. $new_slug = sanitize_title( $new_title );
  54.  
  55. // update post
  56. $recipe_postdata = array(
  57. 'ID' => $post_id,
  58. 'post_title' => $new_title,
  59. 'post_name' => $new_slug,
  60. );
  61.  
  62. if ( ! wp_is_post_revision( $post_id ) ){
  63.  
  64. // unhook this function so it doesn't loop infinitely
  65. remove_action('save_post', 'recipe_update_title');
  66.  
  67. // update the post, which calls save_post again
  68. wp_update_post( $recipe_postdata );
  69.  
  70. // re-hook this function
  71. add_action('save_post', 'recipe_update_title');
  72. }
  73.  
  74. return $value;
  75. }
  76.  
  77. add_filter('acf/update_value/name=recipe_featured_image', 'recipe_update_title', 10, 3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement