Problem: I have a custom field that allows multiple values. I need to be able to count how many items exist in that custom field in each post, so I created a custom shortcode. However, it doesn't seem to work accurately when no items exist. It returns 1 instead of 0.
Solution: In a basic case the following code will work, but if you leave the first instance blank and add content in the following instances, this code will not work. You'll need to add additional logic to handle those cases.
add_shortcode('count_videos', 'count_videos_func'); function count_videos_func($atts, $content){ $atts = shortcode_atts( array( 'field' => '', 'post_id' => get_the_ID(), ), $atts ); $field = get_post_meta($atts['post_id'], $atts['field'], false); $res = 0; if(is_array($field) && $field[0] != ''){ $res = count($field); } return $res; }
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 2 replies, has 2 voices.
Last updated by 5 years, 5 months ago.
Assisted by: Christian Cox.