Notify IndexNow When Content Is Published
Tells search engines that support IndexNow (Bing, Yandex, Seznam and others) about new and updated posts as soon as they are published, so they are crawled sooner.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
$key = get_option( 'wpide_indexnow_key' );
if ( ! $key ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
if ( '/' . $key . '.txt' === $path ) {
status_header( 200 );
header( 'Content-Type: text/plain; charset=utf-8' );
echo esc_html( $key );
exit;
}
}, 0 );
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
if ( 'publish' !== $new_status || 'production' !== wp_get_environment_type() || wp_is_post_revision( $post ) || ! is_post_publicly_viewable( $post ) ) {
return;
}
if ( get_transient( 'wpide_indexnow_' . $post->ID ) ) {
return;
}
set_transient( 'wpide_indexnow_' . $post->ID, 1, MINUTE_IN_SECONDS );
$key = get_option( 'wpide_indexnow_key' );
if ( ! $key ) {
$key = strtolower( wp_generate_password( 32, false, false ) );
update_option( 'wpide_indexnow_key', $key, false );
}
wp_remote_post( 'https://api.indexnow.org/indexnow', array(
'blocking' => false,
'timeout' => 5,
'headers' => array( 'Content-Type' => 'application/json; charset=utf-8' ),
'body' => wp_json_encode( array(
'host' => wp_parse_url( home_url(), PHP_URL_HOST ),
'key' => $key,
'keyLocation' => home_url( '/' . $key . '.txt' ),
'urlList' => array( get_permalink( $post ) ),
) ),
) );
}, 10, 3 );
Notes
Only runs on sites whose environment type is production. A key is generated on first use and served at /your-key.txt as the protocol requires.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.