PluginProbe
Posts Table with Search & Sort / 1.1.1
Posts Table with Search & Sort v1.1.1
1.4.13 trunk 1.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.2 1.3 1.3.1 1.3.1-v2 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.7 All 40 releases
posts-data-table / includes / class-posts-data-table-simple.php

class-posts-data-table-simple.php in Posts Table with Search & Sort 1.1.1, at includes/class-posts-data-table-simple.php

333 lines 10.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * This class is responsible for generating a HTML table from a list of supplied attributes.
5 *
6 * @package Posts_Data_Table
7 * @author Barn2 Media <info@barn2.co.uk>
8 * @license GPL-3.0
9 * @link https://barn2.co.uk
10 * @copyright 2016-2017 Barn2 Media Ltd
11 */
12 // Prevent direct file access
13 if ( !defined( 'ABSPATH' ) ) {
14 exit;
15 }
16
17 class Posts_Data_Table_Simple {
18
19 /**
20 * The complete list of table attributes, and their defaults.
21 */
22 public static $default_args = array(
23 'columns' => 'title,content,date,author,category',
24 'rows_per_page' => 20,
25 'sort_by' => 'date',
26 'sort_order' => '',
27 'category' => '',
28 'tag' => '',
29 'date_format' => 'Y/m/d',
30 'search_on_click' => true,
31 'wrap' => true,
32 'content_length' => 15,
33 'scroll_offset' => 15
34 );
35
36 /**
37 * An array of all possible columns and their default heading, priority, and column width.
38 * Initialised once on construction.
39 */
40 private static $column_defaults = array();
41 private static $allowed_columns = array();
42
43 /**
44 * Stores the number of tables on this page. Used to generate the table ID.
45 */
46 private static $table_count = 1;
47
48 public function __construct() {
49 if ( empty( self::$column_defaults ) ) {
50 /**
51 * Priority values are used to determine visiblity at small screen sizes (1 = highest priority, 6 = lowest priority).
52 * Column widths are automatically calculated by DataTables, but can be overridden by using filter 'posts_data_table_column_defaults'.
53 */
54 self::$column_defaults = array(
55 'id' => array(
56 'heading' => __( 'ID', 'posts-data-table' ),
57 'priority' => 3,
58 'width' => ''
59 ),
60 'title' => array(
61 'heading' => __( 'Title', 'posts-data-table' ),
62 'priority' => 1,
63 'width' => ''
64 ),
65 'category' => array(
66 'heading' => __( 'Categories', 'posts-data-table' ),
67 'priority' => 6,
68 'width' => ''
69 ),
70 'tags' => array(
71 'heading' => __( 'Tags', 'posts-data-table' ),
72 'priority' => 7,
73 'width' => ''
74 ),
75 'date' => array(
76 'heading' => __( 'Date', 'posts-data-table' ),
77 'priority' => 2,
78 'width' => ''
79 ),
80 'author' => array(
81 'heading' => __( 'Author', 'posts-data-table' ),
82 'priority' => 4,
83 'width' => ''
84 ),
85 'content' => array(
86 'heading' => __( 'Content', 'posts-data-table' ),
87 'priority' => 5,
88 'width' => ''
89 )
90 );
91 }
92
93 if ( empty( self::$allowed_columns ) ) {
94 self::$allowed_columns = array_keys( self::$column_defaults );
95 }
96 }
97
98 /**
99 * Retrieves a data table containing a list of posts based on the specified arguments.
100 *
101 * @param array $args An array of options used to display the posts table
102 * @return string The posts table HTML output
103 */
104 public function get_table( $args ) {
105
106 $args = wp_parse_args( $args, self::$default_args );
107
108 if ( empty( $args['columns'] ) ) {
109 $args['columns'] = self::$default_args['columns'];
110 }
111
112 $args['rows_per_page'] = filter_var( $args['rows_per_page'], FILTER_VALIDATE_INT );
113
114 if ( ($args['rows_per_page'] < 1) || !$args['rows_per_page'] ) {
115 $args['rows_per_page'] = false;
116 }
117
118 if ( !in_array( $args['sort_by'], self::$allowed_columns ) ) {
119 $args['sort_by'] = self::$default_args['sort_by'];
120 }
121
122 if ( !in_array( $args['sort_order'], array( 'asc', 'desc' ) ) ) {
123 $args['sort_order'] = self::$default_args['sort_order'];
124 }
125
126 // Set default sort direction
127 if ( !$args['sort_order'] ) {
128 if ( $args['sort_by'] === 'date' ) {
129 $args['sort_order'] = 'desc';
130 } else {
131 $args['sort_order'] = 'asc';
132 }
133 }
134
135 $args['search_on_click'] = filter_var( $args['search_on_click'], FILTER_VALIDATE_BOOLEAN );
136 $args['wrap'] = filter_var( $args['wrap'], FILTER_VALIDATE_BOOLEAN );
137 $args['content_length'] = filter_var( $args['content_length'], FILTER_VALIDATE_INT );
138 $args['scroll_offset'] = filter_var( $args['scroll_offset'], FILTER_VALIDATE_INT );
139
140 if ( empty( $args['date_format'] ) ) {
141 $args['date_format'] = self::$default_args['date_format'];
142 }
143
144 $output = $table_head = $table_body = $body_row_fmt = '';
145
146 // Start building the args needed for our posts query
147 $post_args = array(
148 'post_type' => 'post',
149 'posts_per_page' => apply_filters( 'posts_data_table_post_limit', 1000 ),
150 'post_status' => 'publish',
151 'suppress_filters' => false // Ensure WPML filters run on this query
152 );
153
154 if ( !empty( $args['category'] ) ) {
155 if ( is_numeric( $args['category'] ) ) {
156 $post_args['cat'] = $args['category'];
157 } else {
158 $category = get_category_by_slug( $args['category'] );
159
160 if ( $category ) {
161 $post_args['category_name'] = $category->slug;
162 }
163 }
164 }
165
166 if ( !empty( $args['tag'] ) ) {
167 if ( is_numeric( $args['tag'] ) ) {
168 $post_args['tag_id'] = $args['tag'];
169 } else {
170 $post_args['tag'] = $args['tag'];
171 }
172 }
173
174 // Get all published posts in the current language
175 $all_posts = get_posts( $post_args );
176
177 // Bail early if no posts found
178 if ( !$all_posts || !is_array( $all_posts ) ) {
179 return $output;
180 }
181
182 // Allow theme/plugins to override defaults
183 $column_defaults = apply_filters( 'posts_data_table_column_defaults_' . self::$table_count, apply_filters( 'posts_data_table_column_defaults', self::$column_defaults ) );
184
185 // Get the columns to be used in this table
186 $columns = array_filter( array_map( 'trim', explode( ',', strtolower( $args['columns'] ) ) ) );
187 $hidden_columns = array();
188
189 // If none of the user-specfied columns are valid, use the default columns instead
190 if ( !array_intersect( self::$allowed_columns, $columns ) ) {
191 $columns = explode( ',', self::$default_args['columns'] );
192 }
193
194 // Set hidden columns and sort indexes
195 $table_sort_index = array_search( $args['sort_by'], $columns );
196 $date_sort_index = false;
197 $hidden_date = in_array( 'date', $columns ) || 'date' === $args['sort_by'];
198
199 if ( $hidden_date ) {
200 $hidden_columns[] = 'timestamp';
201 $date_sort_index = count( $columns );
202
203 // If we're sorting by date, make sure we use this hidden column for the initial table sort
204 if ( 'date' === $args['sort_by'] && false === $table_sort_index ) {
205 $table_sort_index = $date_sort_index;
206 }
207 }
208
209 if ( false === $table_sort_index ) {
210 // Sort column is not in list of displayed columns so we'll add it as a hidden column at end of table
211 $hidden_columns[] = $args['sort_by'];
212
213 // Set the table sort index to the index of the hidden sort column
214 $table_sort_index = $date_sort_index ? $date_sort_index + 1 : count( $columns );
215 }
216
217 // Build table header
218 $heading_fmt = '<th data-name="%1$s" data-priority="%2$u" data-width="%3$s"%5$s>%4$s</th>';
219 $cell_fmt = '<td>{%s}</td>';
220
221 foreach ( $columns as $column ) {
222 // Double-check column name is valid
223 if ( !in_array( $column, self::$allowed_columns ) ) {
224 continue;
225 }
226
227 // Do we need to use custom data for ordering this column?
228 $order_data = '';
229
230 if ( 'date' === $column && false !== $date_sort_index ) {
231 $order_data = sprintf( ' data-order-data="%u"', $date_sort_index );
232 }
233
234 // Add heading to table
235 $table_head .= sprintf( $heading_fmt, $column, $column_defaults[$column]['priority'], $column_defaults[$column]['width'], $column_defaults[$column]['heading'], $order_data );
236
237 // Add placeholder to table body format string so that content for this column is included in table output
238 $body_row_fmt .= sprintf( $cell_fmt, $column );
239 }
240
241 foreach ( $hidden_columns as $column ) {
242 $table_head .= sprintf( '<th data-name="%s" data-visible="false"></th>', $column );
243
244 // Make sure data for the hidden column is included in table content
245 $body_row_fmt .= sprintf( $cell_fmt, $column );
246 }
247
248 $table_head = sprintf( '<thead><tr>%s</tr></thead>', $table_head );
249
250 // Build table body
251 $body_row_fmt = '<tr>' . $body_row_fmt . '</tr>';
252
253 // Loop through posts and add a row for each
254 foreach ( (array) $all_posts as $_post ) {
255 setup_postdata( $_post );
256
257 // Format title
258 $title = sprintf( '<a href="%1$s">%2$s</a>', get_permalink( $_post ), get_the_title( $_post ) );
259
260 // Format author
261 $author = sprintf(
262 '<a href="%1$s" title="%2$s" rel="author">%3$s</a>', esc_url( get_author_posts_url( $_post->post_author ) ), esc_attr( sprintf( __( 'Posts by %s', 'posts-data-table' ), get_the_author() ) ), get_the_author()
263 );
264
265 $post_data_trans = array(
266 '{id}' => $_post->ID,
267 '{title}' => $title,
268 '{category}' => get_the_category_list( ', ', '', $_post->ID ),
269 '{tags}' => get_the_tag_list( '', ', ', '', $_post->ID ),
270 '{date}' => get_the_date( $args['date_format'], $_post ),
271 '{author}' => $author,
272 '{content}' => $this->get_post_content( $args['content_length'] ),
273 '{timestamp}' => $_post->post_date
274 );
275
276 $table_body .= strtr( $body_row_fmt, $post_data_trans );
277 } // foreach post
278
279 wp_reset_postdata();
280
281 $table_body = sprintf( '<tbody>%s</tbody>', $table_body );
282
283 $paging_attr = 'false';
284 if ( ( $args['rows_per_page'] > 1 ) && ( $args['rows_per_page'] < count( $all_posts ) ) ) {
285 $paging_attr = 'true';
286 }
287
288 // Order attribute should be escaped here rather than in sprintf below as we don't want to escape the double-quotes around "asc" or "desc"
289 $order_attr = ( $table_sort_index === false ) ? '' : sprintf( '[[%u, "%s"]]', esc_attr( $table_sort_index ), esc_attr( $args['sort_order'] ) );
290 $offset_attr = ( $args['scroll_offset'] === false ) ? 'false' : $args['scroll_offset'];
291
292 $table_class = 'posts-data-table';
293 if ( !$args['wrap'] ) {
294 $table_class .= ' nowrap';
295 }
296
297 $output = sprintf(
298 '<table '
299 . 'id="posts-table-%1$u" '
300 . 'class="%2$s" '
301 . 'data-page-length="%3$u" '
302 . 'data-paging="%4$s" '
303 . 'data-order=\'%5$s\' '
304 . 'data-click-filter="%6$s" '
305 . 'data-scroll-offset="%7$s" '
306 . 'cellspacing="0" width="100%%">'
307 . '%8$s%9$s' .
308 '</table>', self::$table_count, esc_attr( $table_class ), esc_attr( $args['rows_per_page'] ), esc_attr( $paging_attr ), $order_attr, ( $args['search_on_click'] ? 'true' : 'false' ), esc_attr( $offset_attr ), $table_head, $table_body
309 );
310
311 // Increment the table count
312 self::$table_count++;
313
314 return $output;
315 }
316
317 /**
318 * Retrieve the post content, truncated to the number of words specified by $num_words.
319 *
320 * Must be called with the Loop or a secondary loop after a call to setup_postdata().
321 *
322 * @param int $num_words The number of words to trim the content to
323 * @return string The (truncated) post content
324 */
325 private function get_post_content( $num_words = 15 ) {
326 $text = get_the_content( '' );
327 $text = strip_shortcodes( $text );
328 $text = apply_filters( 'the_content', $text );
329 $text = wp_trim_words( $text, $num_words, ' &hellip;' );
330 return $text;
331 }
332
333 }