SergeyBiryukov

Auto-populate post title from featured image title

May 12th, 2014
511
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. function get_featured_image_title( $post_id )  {
  2.     $attachment_id = get_post_thumbnail_id( $post_id );
  3.     if ( ! $attachment_id ) {
  4.         return false;
  5.     }
  6.  
  7.     $attachment_data = wp_get_attachment_metadata( $attachment_id );
  8.     if ( ! isset( $attachment_data['image_meta']['title'] ) ) {
  9.         return false;
  10.     }
  11.  
  12.     return $attachment_data['image_meta']['title'];
  13. }
  14.  
  15. function disable_empty_content_check( $maybe_empty, $postarr ) {
  16.     if ( ! $maybe_empty ) {
  17.         return $maybe_empty;
  18.     }
  19.  
  20.     if ( 'showcase' !== $postarr['post_type'] ) {
  21.         return $maybe_empty;
  22.     }
  23.  
  24.     if ( wp_is_post_revision( $postarr['ID'] ) ) {
  25.         return $maybe_empty;
  26.     }
  27.  
  28.     if ( get_featured_image_title( $postarr['ID'] ) ) {
  29.         $maybe_empty = false;
  30.     }
  31.  
  32.     return $maybe_empty;
  33. }
  34. add_filter( 'wp_insert_post_empty_content', 'disable_empty_content_check', 10, 2 );
  35.  
  36. function auto_populate_post_title( $data, $postarr ) {
  37.     if ( 'showcase' !== $postarr['post_type'] ) {
  38.         return $data;
  39.     }
  40.  
  41.     if ( wp_is_post_revision( $postarr['ID'] ) ) {
  42.         return $data;
  43.     }
  44.  
  45.     $featured_image_title = get_featured_image_title( $postarr['ID'] );
  46.     if ( ! $data['post_title'] && $featured_image_title ) {
  47.         $data['post_title'] = $featured_image_title;
  48.     }
  49.  
  50.     return $data;
  51. }
  52. add_filter( 'wp_insert_post_data', 'auto_populate_post_title', 10, 2 );
Advertisement
Add Comment
Please, Sign In to add comment