Skip to content

Instantly share code, notes, and snippets.

@Bobz-zg
Last active August 24, 2025 09:53
Show Gist options
  • Select an option

  • Save Bobz-zg/aa86aa5f5bd5023387d634ec54ad8790 to your computer and use it in GitHub Desktop.

Select an option

Save Bobz-zg/aa86aa5f5bd5023387d634ec54ad8790 to your computer and use it in GitHub Desktop.
Additional content for Yoast SEO Content analysis
<?php
// Enqueue the custom Yoast Analysis JavaScript in the WordPress admin editor.
add_action( 'admin_enqueue_scripts', function( $hook ) {
// Only load the script on post editing screens ('post.php' for edit, 'post-new.php' for new posts).
if ( in_array( $hook, [ 'post.php', 'post-new.php' ], true ) ) {
// Build the full URL to the JavaScript file in the theme's 'js' directory.
$script_path = get_template_directory_uri() . '/js/yoast-analysis.js';
// Enqueue the script with a handle 'yoast-analysis'.
// Load it in the footer (true), with jQuery as a dependency.
wp_enqueue_script(
'yoast-analysis',
$script_path,
[ 'jquery' ], // You can add 'yoast-seo-post-scraper' here if needed.
null, // No specific version is set.
true // Load script in the footer for better performance.
);
// Pass useful PHP data to JavaScript via a global object 'pumpkin'.
global $post; // Access current post object.
if ( $post ) {
wp_localize_script(
'yoast-analysis', // Script handle to attach data to.
'pumpkin', // Name of the JS object that will hold the data.
[
'ajax_url' => admin_url( 'admin-ajax.php' ), // AJAX URL for backend requests.
'post_id' => $post->ID, // Current post ID.
'post_type' => $post->post_type, // Current post type.
]
);
}
}
} );
// Register AJAX actions to handle requests from both logged-in and guest users.
// This points to the function below that serves the post content.
add_action( 'wp_ajax_codesoup_get_yoast_post_content', 'codesoup_get_yoast_post_content' );
add_action( 'wp_ajax_nopriv_codesoup_get_yoast_post_content', 'codesoup_get_yoast_post_content' );
/**
* AJAX handler returning the post content plus optional custom fields.
*/
function codesoup_get_yoast_post_content() {
// Check if the post_id was provided in the AJAX POST request.
if ( empty( $_POST['post_id'] ) ) {
wp_send_json_error( 'No post ID provided' );
}
// Sanitize and cast the post_id to integer.
$post_id = intval( $_POST['post_id'] );
$post = get_post( $post_id );
// If no post found for the given ID, return an error.
if ( ! $post ) {
wp_send_json_error( 'Post not found' );
}
// Start with the standard post content.
$content = $post->post_content;
// OPTIONAL: Append any custom fields or ACF field content to the analysis string.
// Example: $content .= get_field('my_acf_field', $post_id );
// Return the combined content as a successful JSON response.
wp_send_json_success( $content );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment