Tell us what you are trying to do?
I want to show in a view posts order by specific child posts count.
Is there any documentation that you are following?
No.
Is there a similar example that we can see?
https://toolset.com/forums/topic/ordering-in-views-parent-posts-with-number-of-child-posts-descending/#post-630562
This is the code that I use. But I have this situation when my child post are created, the parent post custom field "sea_service_vessel" is related with Post Reference in child CPT fields. The strange thing is that I can not find the 'meta_key' "_wpcf_sea_service_vessel" for this post.
Parent Post "vessel"
Child Post "seaman-sea-service"
add_action( 'before_delete_post', 'count_total_children_delete' );
function count_total_children_delete($post_id)
{
if ( get_post_type( $post_id ) == 'cred-comment' ) {
$parent_id = get_post_meta( $post_id, '_wpcf_sea_service_vessel', true );
if($parent_id != '')
{
$childargs = array(
'post_type' => 'seaman-sea-service',
'numberposts' => -1,
'meta_key' => '_wpcf_sea_service_vessel',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(array('key' => '_wpcf_sea_service_vessel', 'value' => $parent_id))
);
$totalChildCount = count(get_posts($childargs));
update_post_meta( $parent_id, 'wpcf-child-count', $totalChildCount);
}
}
}
add_action( 'save_post', 'count_total_children',20,2);
function count_total_children($post_id){
if ( get_post_type( $post_id ) == 'cred-comment' ) {
$parent_id = get_post_meta( $post_id, '_wpcf_sea_service_vessel', true );
if($parent_id != '')
{
$childargs = array(
'post_type' => 'cred-comment',
'numberposts' => -1,
'meta_key' => '_wpcf_sea_service_vessel',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(array('key' => '_wpcf_sea_service_vessel', 'value' => $parent_id))
);
$totalChildCount = count(get_posts($childargs));
$oldChildCount=get_post_meta( $parent_id, 'wpcf-child-count', true );
if( $totalChildCount != $oldChildCount ){
update_post_meta( $parent_id, 'wpcf-child-count', $totalChildCount );
}
}
}
if ( get_post_type( $post_id ) == 'lawyer' ) {
$count=get_post_meta( $post_id, 'wpcf-child-count', true );
if($count == ''){
add_post_meta($post_id, 'wpcf-child-count',0);
}
}
}