I’m assuming you’re referring to the header.php
file of your theme. In that case, it’s as easy as just enqueueing the script by appending this function to your theme’s functions.php
file:
function enqueue_facebook_javascript_sdk(): void {
wp_enqueue_script( 'facebook-javascript-sdk-initializer', get_template_directory_uri() . '/path/to/your/initializer.js' );
wp_enqueue_script( 'facebook-javascript-sdk', 'https://connect.facebook.net/en_US/sdk.js', array(), null );
return;
}
add_action( 'wp_enqueue_scripts', 'enqueue_facebook_javascript_sdk' );
The first JavaScript file should contain your version of the initializer from the docs, containing your appId
.
In addition, the script requires the async
and defer
attributes. To add these, we insert a second function into functions.php
:
function add_async_attribute( string $tag, string $handle ): string {
if ( 'facebook-javascript-sdk' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' async defer src', $tag );
}
add_filter( 'script_loader_tag', 'add_async_attribute', 10, 2 );
Please let me know if this works for you.