Support » Fixing WordPress » Add sum of custom field values in sidebar

  • Kzmi

    (@terrorjunk)


    Hello,

    Im looking to add the sum of custom field values from topics into my sidebar.
    Lets say I have a custom field on every post, the total value of those custom fields is 5214, I want it to show that number in the sidebar.

    I tried several snippets I found online but can’t really seem to find anything that does the job.

    Thanks in advance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi @terrorjunk.,

    You can achieve this requirement using this function

    $key_1_value = get_post_meta( get_the_ID(), 'key_1', true );
    if ( ! empty( $key_1_value ) ) {
        echo $key_1_value;
    }

    https://developer.wordpress.org/reference/functions/get_post_meta/

    Just try this

    Thanks
    Rajan V

    Hello,

    The idea here would be to make a WP_Query and within your while loop where posts are returned to read your meta field with get_post_meta() and just add it to itself as an integer.

    Reference :
    https://codex.wordpress.org/Class_Reference/WP_Query
    https://developer.wordpress.org/reference/functions/get_post_meta/

    The best approach would be through a custom plugin that created either a widget or just a shortcode to run that code and return the number to you.

    If you want further help I’ll be happy to assist.

    Thread Starter Kzmi

    (@terrorjunk)

    @rajanit2000

    Thanks for the snippet, I’m unsure where to enter it and how to use it.
    Also, this snippet only gets data from one post right?

    @xkon

    Thank you, I must say I’m a beginner, I’ve been messing around a little bit but can’t really seem to achieve something.

    Hey,

    The code below is not fully optimized etc as I’m writing it leaving work but it certainly works and it’s a start for you to get the idea of the loop I was talking about.

    
    <?php
    	$query = new WP_Query( array( 'category_name' => 'category-here' ) );
    	if ( $query->have_posts() ) {
    		$num = 0;
    		while ( $query->have_posts() ) {
    				$query->the_post();
    				$num = $num + get_post_meta( get_the_id(), 'my_key', true );
    		}
    		echo $num;
    		wp_reset_postdata();
    	}
    ?>

    This will basically make a WP_Query for all posts that are in the category with the slug category-here and sum up whatever is inside a meta field named my_key.

    This will ofcourse work even if you add the code straight into your themes files and make the necessary adjustments to fit your needs of meta field name and posts etc but there is always room for improvement and proper use ( as I said it would be better through a plugin with a shortcode for example ).

    I hope you find this somewhat helpful even for a start to work your way through the logic.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add sum of custom field values in sidebar’ is closed to new replies.