Can I use the API and a JS ajax function to get the two values?
Yes, absolutely.
Step 1: (PHP) Registers the custom fields (i.e. add them to the WordPress REST API response for Posts)
register_meta( 'post', 'address1', [
'type' => 'string', // string/boolean/integer/number
'single' => true,
'show_in_rest' => true,
] );
register_meta( 'post', 'address2', [
'type' => 'string',
'single' => true,
'show_in_rest' => true,
] );
See Modifying Responses | REST API Handbook and register_meta()
.
Step 2 (PHP): Loads the official client/JS library
add_action( 'wp_enqueue_scripts', function(){
wp_enqueue_script( 'wp-api' );
} );
See Backbone JavaScript Client | REST API Handbook.
Step 3: Add the JS code
.. which is as simple as: (refer to your question for the postId
variable)
var post = new wp.api.models.Post( { id: postId } );
post.fetch().done( function(){
// Use `post.getMeta( 'KEY' )` to retrieve the meta value.
alert( post.getMeta( 'address1' ) );
alert( post.getMeta( 'address2' ) );
} );
UPDATE: An alternative to the wp-api
script.
If you don’t want to use the official client/JS library, or if you want just a simple jQuery script, then…
Step 2:
Don’t queue/load the wp-api
script.
Add this somewhere on the page: (the variable name can be changed, but make sure to also change the one in the JS code in step #3)
<script>
var restApiSettings = {
nonce: '<?= wp_create_nonce( 'wp_rest' ) ?>',
root: '<?= esc_url_raw( rest_url( 'wp/v2' ) ) ?>'
};
</script>
Or with PHP/WordPress, use wp_localize_script()
like the official client/JS library does it.
wp_localize_script( 'your-script', 'restApiSettings', [
'root' => esc_url_raw( rest_url( 'wp/v2' ) ),
'nonce' => wp_create_nonce( 'wp_rest' )
] );
Step 3: The JS/jQuery code:
jQuery.get( restApiSettings.root + '/posts/' + postId, {
_wpnonce: restApiSettings.nonce
}, function( res ){
if ( res.meta ) {
alert( res.meta.address1 );
alert( res.meta.address2 );
}
} );