I’ll show you how I’ve taken this script and used it in a shortcode.
Plugin
add_shortcode('my-shortcode', 'my_shortcode_function');
function my_shortcode_function($atts){
$hello = $atts['hello'];
$nonce = wp_create_nonce('my-nonce');
$output = "<script type='text/javascript'>
<!--
jQuery(function($){
$('li.wp-block-post').each(function(index, element){
$($(this).attr('class').split(' ')).each(function(){
var c = this.split('post-');
if(c[1]){
if($.isNumeric(c[1])){
console.log('Post ID: ' + c[1]);
var your_php_file = '../my-file.php',
response = '',
data = {
nonce: '" . $nonce . "',
post_id: c[1]
};
jQuery.post(your_php_file, data, function(response){
if(response != ''){
console.log('Result: ' + response);
} else {
console.log('Error');
}
});
}
}
});
});
});
-->
</script>";
$output .= $hello;
return $output;
}
That script creates the shortcode my-shortcode which calls my_shortcode_function.
The $atts attribute is available for passing values from the shortcode to the script.
I included an $atts example where the text “Hello!” is handed to the script, and then it’s handed back to the page where it is subsequently printed.
wp_create_nonce creates a security token for the JavaScript AJAX request.
my-file.php contains the script that fetches the Post meta and returns it to the JavaScript.
my-file.php
<?php
require('wp-load.php');
if(!wp_verify_nonce($_REQUEST['nonce'], 'my-nonce') || !isset($_REQUEST['post_id']) || !is_numeric($_REQUEST['post_id'])){
die('Validation Failed');
}
echo get_post_meta($_REQUEST['post_id'], 'my_custom_field_name', true);
?>
This PHP script loads the WordPress environment, validates the security token, nonce, and checks if the post_id variable is in fact a number.
If the submission was valid, get_post_meta() retrieves the specific custom field, “my_custom_field_name“
Each Post/Page is given the custom field, “my_custom_field_name“. The values will be printed to the console when this script runs.
Shortcode
[my-shortcode hello="Hello!"]
This shortcode is placed only once in the same Page/Post as the Query Loop Block.
I hope you find this information helpful.