Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Count table rows (<tr>) in the original post content.
- *
- * To count all table rows:
- * 1) If in the loop: echo table_rows_count()
- * 2) If not, specify post ID: echo table_rows_count( 123 )
- *
- * To count table rows which contains a specific string:
- * 1) If in the loop: echo table_rows_count( null, 'the string' )
- * 2) If not, specify post ID: echo table_rows_count( 123, 'the string' )
- *
- * In single.php or any singular post template files, you may need to call
- * wp_reset_query() like so:
- * wp_reset_query();
- * echo table_rows_count();
- *
- * This function would work well so long as your tables use valid HTML code.
- * E.g. Escape > to < when used in an attribute (e.g. data-foo="Bar <"),
- * and always close a <tr> with a </tr>.
- */
- // YOU CAN COPY JUST THE FUNCTION BELOW WITHOUT THE ABOVE COMMENTS SECTION...
- function table_rows_count( $post = null, $string = '' ) {
- $post_content = get_post_field( 'post_content', $post );
- $rows = preg_split( '#<tr\b(.*?)>#', $post_content );
- $rows_count = 0;
- $count_only = ( strlen( trim( $string ) ) < 1 );
- foreach ( (array) $rows as $row ) {
- if ( false === stripos( $row, '</tr>' ) ) {
- continue;
- }
- if ( $count_only ) {
- $rows_count++;
- continue;
- }
- if ( false !== stripos( $row, $string ) ) {
- $rows_count++;
- }
- }
- return $rows_count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement