-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtablepress-scoped-headers.php
64 lines (57 loc) · 2.07 KB
/
tablepress-scoped-headers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
/**
* TablePress Scoped Headers Plugin.
*
* @package TablePressScopedHeaders
* @link https://equalizedigital.com/
* @since 1.0.0
*
* @wordpress-plugin
* Plugin Name: TablePress Scoped Headers Plugin
* Plugin URI: https://equalizedigital.com/
* Description: Adds scope attributes to table headers in TablePress tables for improved accessibility.
* Version: 1.0.0
* Author: Equalize Digital
* Author URI: https://equalizedigital.com
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: tablepress-scoped-headers
*/
namespace EqualizeDigital\TablePressScopedHeaders;
// Prevent direct access to the file.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Add scope attributes to table headers.
*
* @param string $output HTML output of the table.
* @param mixed $table Table object.
* @param array $render_options Render options.
* @return string HTML output of the table.
*/
function add_scope_to_table_headers( $output, $table, $render_options ) {
$dom = new \DOMDocument();
libxml_use_internal_errors( true ); // Suppress warnings for invalid HTML.
// Set encoding to UTF-8
$output = mb_convert_encoding( $output, 'HTML-ENTITIES', 'UTF-8' );
$dom->loadHTML( '<!DOCTYPE html><html><body>' . $output . '</body></html>' );
libxml_clear_errors();
$xpath = new \DOMXPath( $dom );
if ( isset( $render_options['table_head'] ) && $render_options['table_head'] ) {
$th = $xpath->query( '//thead/tr/th' );
foreach ( $th as $node ) {
$node->setAttribute( 'scope', 'col' );
}
}
if ( isset( $render_options['first_column_th'] ) && $render_options['first_column_th'] ) {
$th = $xpath->query( '//tbody/tr/th' );
foreach ( $th as $node ) {
$node->setAttribute( 'scope', 'row' );
}
}
$output = $dom->saveHTML();
$output = preg_replace( '~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $output ); // Remove added html/body tags
return $output;
}
add_filter( 'tablepress_table_output', __NAMESPACE__ . '\\add_scope_to_table_headers', 10, 3 );