I found out that actually, in a new Post creation, the Post Meta is not actually available yet! I was trying to get something that wasn’t available!
Check – How to access the post meta of a post that has just been published? …. which says … “when you publish the post and ‘publish_post’ is called, the post meta is not yet saved in the database”.
Thanks to Nicolai, I used $_Post[FormFeild]
to get the required details!
This is my working code, line 6 ($the_book_ID = $_POST['input_2'];
) got everything working!
function on_CPT_request_publish( $ID, $post ) {
// ----------------- Start of Function -----------------
// -------------------- Grab details to work with -----------------------
// Get book ID
$the_book_ID = $_POST['input_2'];
// Get reviewer count
$the_requested_reviews = $_POST['input_16'];
// Grab the number before the pipe for e.g. 3|69 would = 3
$vars = explode('|', $the_requested_reviews);
$the_requested_reviews = $vars[0];
// Get Book details
$post_book_details = get_post( $the_book_ID );
$book_title = $post_book_details->post_title;
$the_book_genre_ID = get_post_meta($the_book_ID,'book_genre',true);
$theBookAuthor = $post_book_details->post_author;
// ----------------- Find users -------------------
// WP_User_Query arguments
$args = array (
'number' => $the_requested_reviews,
'count_total' => true,
'role' => 'Subscriber',
'order' => 'ASC',
'orderby' => 'user_registered',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'user_book_genres',
'value' => $the_book_genre_ID,
'compare' => '='
),
array(
'key' => 'user_type',
'value' => 'Reviewer',
'compare' => '='
),
array(
'key' => 'user_credits',
'value' => '1',
'compare' => '>='
)
)
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query( $args );
// Get the results
$ARCusers = $wp_user_query->get_results();
// Check for results
if ( ! empty( $ARCusers ) ) {
// loop through each author
foreach ( $ARCusers as $ARCuser ) {
//Do the magic!
// get all the user's data
$ReviewAuthorID = $ARCuser->ID;
//https://wordpress.stackexchange.com/questions/106973/wp-insert-post-or-similar-for-custom-post-type
$review_post_id = wp_insert_post(array (
'post_type' => 'review',
'post_title' => 'Review of book - ' . $book_title . ' - ' . $ReviewAuthorID,
'post_author' => $ReviewAuthorID,
'post_status' => 'publish',
'comment_status' => 'closed', // if you prefer
'ping_status' => 'closed', // if you prefer
));
if ($review_post_id) {
// insert post meta
add_post_meta($review_post_id, 'review_book_id', $the_book_ID);
add_post_meta($review_post_id, 'book_author_id', $theBookAuthor);
}
}
}
// ----------------- End of Function -----------------
}
add_action( 'publish_request', 'on_CPT_request_publish', 10, 2 );