Hello -
Here is my setup:
- "book" CPT listing books
- "practitioner" CPT listing practitioners
- "reco-book" CPT listing book recommendations made by practitioners, and which is a child post of "book" and "practitioner" to implement a many-to-many relationship
- CRED form to post new recommendations displayed on the "book" post template: this form just shows the submit button with the "recommend" text, and creates a new "reco-book" post with the correct "book" and "practitioner" parents
- total number of recommenders is displayed in the "book" template correctly by using the following shortcode
// BOOK RECOMMENDERS: shortcode to count them to display count on post page
add_shortcode('book-reco-count', 'book_reco_count_func');
function book_reco_count_func()
{
$child_posts = types_child_posts('book-reco');
return count($child_posts);
};
Now, I want to be able to use the total number of recommenders easily in my Views/Layouts modules. Here, I have 2 questions:
1) It seems the easiest way to do this is to record the total number of recommendations in a custom field. Is this correct or is there a better alternative?
2) If a custom field is the best way, then what is the best way to implement this? I have a working solution using the code below:
// CRED form action to count recommenders
add_action('cred_save_data_160', 'jln_add_book_id',10,2);
function jln_add_book_id($post_id, $form_data)
{
$parent_id = get_post_meta($post_id, '_wpcf_belongs_book_id', true);
$result = new WP_Query(array(
'post_type' => 'book-reco', // your child CPT slug
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_wpcf_belongs_book_id',
'value' => $parent_id,
'compare' => 'LIKE',
),
),
'posts_per_page' => -1, // can result in performance issues!
));
$book_recommenders = count($result->posts);
update_post_meta($parent_id, 'wpcf-total-recommenders-book', $book_recommenders);
}
This works well and basically uses the fact that new Recommendations are always added through the same CRED form to count the total number of recommendations made so far each time the CRED form is submitted and update the appropriate custom post field.
However, this can certainly result in performance issues since I have to count every posts, and this CRED form is going to be heavily used.
Would you be able to point me towards another, simpler and more robust of achieving this? There might even be a built-in way to do this 🙂
Many thanks!
Best,
- Julien