Advertisement
5ally

(WordPress) table_rows_count()

Dec 14th, 2018
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | None | 0 0
  1. /**
  2.  * Count table rows (<tr>) in the original post content.
  3.  *
  4.  * To count all table rows:
  5.  *   1) If in the loop:          echo table_rows_count()
  6.  *   2) If not, specify post ID: echo table_rows_count( 123 )
  7.  *
  8.  * To count table rows which contains a specific string:
  9.  *   1) If in the loop:          echo table_rows_count( null, 'the string' )
  10.  *   2) If not, specify post ID: echo table_rows_count( 123, 'the string' )
  11.  *
  12.  * In single.php or any singular post template files, you may need to call
  13.  * wp_reset_query() like so:
  14.  *   wp_reset_query();
  15.  *   echo table_rows_count();
  16.  *
  17.  * This function would work well so long as your tables use valid HTML code.
  18.  * E.g. Escape > to &lt; when used in an attribute (e.g. data-foo="Bar &lt;"),
  19.  * and always close a <tr> with a </tr>.
  20.  */
  21. // YOU CAN COPY JUST THE FUNCTION BELOW WITHOUT THE ABOVE COMMENTS SECTION...
  22. function table_rows_count( $post = null, $string = '' ) {
  23.     $post_content = get_post_field( 'post_content', $post );
  24.     $rows = preg_split( '#<tr\b(.*?)>#', $post_content );
  25.     $rows_count = 0;
  26.  
  27.     $count_only = ( strlen( trim( $string ) ) < 1 );
  28.     foreach ( (array) $rows as $row ) {
  29.         if ( false === stripos( $row, '</tr>' ) ) {
  30.             continue;
  31.         }
  32.  
  33.         if ( $count_only ) {
  34.             $rows_count++;
  35.             continue;
  36.         }
  37.  
  38.         if ( false !== stripos( $row, $string ) ) {
  39.             $rows_count++;
  40.         }
  41.     }
  42.  
  43.     return $rows_count;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement