Advanced patterns for working with Google Search Console data in custom code.
Building a Custom Dashboard Widget
php
add_action( 'wp_dashboard_setup', function () {
if ( ! class_exists( 'SEOFORGE_GSC' ) || ! SEOFORGE_GSC::instance()->is_connected() ) {
return;
}
wp_add_dashboard_widget( 'my_gsc_widget', 'Top Keywords (GSC)', function () {
$rankings = SEOFORGE_GSC::instance()->get_keyword_rankings( 28, 10 );
echo '<table><thead><tr><th>Keyword</th><th>Clicks</th><th>Position</th></tr></thead><tbody>';
foreach ( $rankings as $r ) {
echo '<tr><td>' . esc_html( $r['keyword'] ) . '</td>'
. '<td>' . intval( $r['clicks'] ) . '</td>'
. '<td>' . number_format( $r['position'], 1 ) . '</td></tr>';
}
echo '</tbody></table>';
} );
} );Exporting GSC Data to CSV
php
$gsc = SEOFORGE_GSC::instance();
if ( ! $gsc->is_connected() ) {
return;
}
$rankings = $gsc->get_keyword_rankings( 90, 500 );
$csv = "Keyword,Clicks,Impressions,CTR,Positionn";
foreach ( $rankings as $r ) {
$csv .= sprintf(
""%s",%d,%d,%.1f,%.1fn",
str_replace( '"', '""', $r['keyword'] ),
$r['clicks'],
$r['impressions'],
$r['ctr'],
$r['position']
);
}
file_put_contents( WP_CONTENT_DIR . '/gsc-export.csv', $csv );Correlating GSC Data with SEO Scores
php
$gsc = SEOFORGE_GSC::instance();
$analyzer = SEOFORGE_Analyzer::instance();
$page_rankings = $gsc->get_keyword_rankings( 28, 50 );
$report = [];
foreach ( $page_rankings as $r ) {
// Find the post ID from the ranking URL
$post_id = url_to_postid( $r['url'] ?? '' );
if ( ! $post_id ) {
continue;
}
$cached = $analyzer->get_cached( $post_id );
$report[] = [
'keyword' => $r['keyword'],
'position' => $r['position'],
'clicks' => $r['clicks'],
'seo_score' => $cached ? (int) $cached->score : 0,
];
}—