add_action('save_post', 'set_focus_keyphrase_from_title_and_body', 20, 2); function set_focus_keyphrase_from_title_and_body($post_id, $post) { // Only apply to published posts/pages if (!in_array($post->post_type, ['post', 'page']) || $post->post_status !== 'publish') { return; } // Prevent infinite loop remove_action('save_post', 'set_focus_keyphrase_from_title_and_body', 20); // Check if already set $existing = get_post_meta($post_id, '_yoast_wpseo_focuskw', true); if (!empty($existing)) { return; } // Get title and body content $title = get_the_title($post_id); $body = strip_tags($post->post_content); $body = wp_trim_words($body, 20, ''); // Combine title and body for keyword context $source_text = strtolower($title . ' ' . $body); // Clean and tokenize $source_text = preg_replace('/[^a-z0-9\s]/', '', $source_text); // remove punctuation $words = array_unique(explode(' ', $source_text)); // Remove common stopwords $stop_words = ['the', 'and', 'for', 'with', 'from', 'this', 'that', 'your', 'are', 'you', 'was', 'were', 'have', 'has', 'had', 'of', 'to', 'in', 'on', 'at', 'by', 'an', 'be', 'it']; $keywords = array_diff($words, $stop_words); // Choose top 3–5 words $focus_keyphrase = implode(' ', array_slice($keywords, 0, 5)); // Save the Focus Keyphrase to Yoast update_post_meta($post_id, '_yoast_wpseo_focuskw', sanitize_text_field($focus_keyphrase)); // Re-enable hook add_action('save_post', 'set_focus_keyphrase_from_title_and_body', 20, 2); }
July 1, 2025

Leave a Reply

WordPress Ads
Log In