PluginProbe
Posts Table with Search & Sort / 1.3.1
Posts Table with Search & Sort v1.3.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 / src / Simple_Posts_Table.php

Simple_Posts_Table.php in Posts Table with Search & Sort 1.3.1, at src/Simple_Posts_Table.php

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