Support

Account

Home Forums General Issues How to show total of a custom field based on a date range in Repeater Field

Helping

How to show total of a custom field based on a date range in Repeater Field

  • I want to make monthly reports of Payments received.

    I have a custom post type – person
    I have created a repeater field ‘Deals’ for this CPT.
    In Repeater field ‘Deals’ – I have two subfields –
    1. deal_payment_received
    2. deal_payment_received_date

    I want to show sum of all custom sub field ‘deal_payment_received’ in a date range.

    I am using following code.
    This code is not showing correct value.
    This code is actually showing sum of all deals of a person which are also not in date range.

    <?php 
    
    $args = array(
    	'post_type'	=> 'person',  
    	'meta_query'	=> array(
    	 	array(
    			'key'		=> 'deals_%_deal_payment_received_date',
    			'compare'	=> 'BETWEEN',
    			'value'		=> array('20161201', '20161231'),
    		),
    		
    	)
    	);
     
    $the_query = new WP_Query( $args );
    $count = 0;
     
    ?>
     <?php if( $the_query->have_posts() ): ?>
    	<ul>
    	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    		<li>
    			<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    			<?php if(get_field('deals', $the_query->ID)): ?>
    	 			 <?php while(has_sub_field('deals', $the_query->ID)): ?>
    					 
    						 <?php $count  += intval( get_sub_field('deal_payment_received', $the_query->ID)); ?>
    				 <?php endwhile; ?>
    			   <?php endif; ?>
    		</li>
    	<?php endwhile; ?>
    	</ul>
    <?php endif; ?>
    <?php  echo "Total Deal Values <h1>" . $count . "</h1>"; ?>
     
    <?php wp_reset_query();	 // Restore global post data stomped by the_post(). ?>
    
    ----
    //functions.php
    
    function my_posts_where( $where ) {
    	
    	$where = str_replace("meta_key = 'deals_%", "meta_key LIKE 'deals_%", $where);
    
    	return $where;
    }
    add_filter('posts_where', 'my_posts_where');

    —-

    Kindly Guide me where I am wrong.

  • You’re doing everything according to the documentation, the only thing that I can think of is that the where is not being changed properly, you need to look at the where.

    
    function my_posts_where( $where ) {
    	// this will put the where into the error log so you can open
            // the error log an look at it
            error_log($where);
    	$where = str_replace("meta_key = 'deals_%", "meta_key LIKE 'deals_%", $where);
            error_log($where);
    
    	return $where;
    }
    add_filter('posts_where', 'my_posts_where');
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘How to show total of a custom field based on a date range in Repeater Field’ is closed to new replies.