diff --git a/enfold-cille/functions.php b/enfold-cille/functions.php index 7582f91..29c21bf 100644 --- a/enfold-cille/functions.php +++ b/enfold-cille/functions.php @@ -159,13 +159,32 @@ function avia_change_breadcrumb( $trail, $args ) { } /* - * Adapting content for social networks; and auto generate title if it is empty. + * Auto generate the post title if it's empty and post has content. */ -add_action( 'save_post', 'adapting_social_post', 1, 2 ); -function adapting_social_post( $post_id, $post ) { - // Unhook this function so it doesn't loop infinitely: - remove_action( 'save_post', 'adapting_social_post', 1, 2 ); +add_filter( 'wp_insert_post_data', 'autogenerate_title', 1, 2 ); +function autogenerate_title( $data, $postarr ) { + $title = preg_replace( '!\s+!', ' ', str_replace( ' ', ' ', $data['post_title'] ) ); + $text_title = trim( strip_tags( $title ) ); + if ( empty( $text_title ) ) { + $content = preg_replace( '!\s+!', ' ', str_replace( ' ', ' ', $data['post_content'] ) ); + $text_content = trim( strip_tags( $content ) ); + + if ( ! empty( $text_content ) ) { + $content_words = explode( ' ', $text_content ); + $text_title = implode( ' ', array_slice( $content_words, 0, 4 ) ); + $data['post_title'] = count( $content_words ) > 4 ? "$text_title …" : $text_title; + } + } + + return $data; +} + +/* + * Sharing content in social networks if required. + */ +add_action( 'save_post', 'share_post', 1, 2 ); +function share_post( $post_id, $post ) { // Count post categories: $post_categories = get_the_category( $post_id ); $categories = array_values( array_column( $post_categories, 'name' ) ); @@ -176,71 +195,64 @@ function adapting_social_post( $post_id, $post ) { // Nothing to do if there aren't social categories: if ( $num_social_categories > 0 ) { - // Get clean post title: + // Get cleaned post title: $title = preg_replace( '!\s+!', ' ', str_replace( ' ', ' ', $post->post_title ) ); $text_title = trim( strip_tags( $title ) ); if ( mb_strrpos( $text_title, ' …' ) == mb_strlen( $text_title ) - 2 ) { $text_title = mb_substr( $text_title, 0, mb_strlen( $text_title ) - 2 ); } - // Get clean post content: + // Get cleaned post content: $content = preg_replace( '!\s+!', ' ', str_replace( ' ', ' ', $post->post_content ) ); $text_content = trim( strip_tags( $content ) ); - // Nothing to do if no title and no content: - if ( ! empty( $text_title ) || ! empty( $text_content ) ) { - // Adapting content for pure social posts: - if ( $num_categories == $num_social_categories ) { - $post_content = trim( strip_tags( $content, '