1+ <?php
2+
3+ /**
4+ *
5+ */
6+ class Shapely_Builder {
7+
8+ private static $ instance = null ;
9+
10+ private $ pages = array ();
11+ private $ sidebars = array ();
12+
13+ function __construct () {
14+
15+ $ this ->get_all_pages ();
16+
17+ // Hooks
18+ if ( ! empty ( $ this ->pages ) ) {
19+
20+ add_action ( 'widgets_init ' , array ( $ this , 'register_sidebars ' ) );
21+ add_action ( 'customize_controls_enqueue_scripts ' , array ( $ this , 'enqueue_builder_js ' ) );
22+ add_filter ( 'sidebars_widgets ' , array ( $ this , 'remove_specific_widget ' ) );
23+
24+ }
25+
26+ }
27+
28+ public function get_all_pages () {
29+
30+ $ args = array (
31+ 'post_type ' => 'page ' ,
32+ 'posts_per_page ' => -1 ,
33+ 'meta_query ' => array (
34+ array (
35+ 'key ' => '_wp_page_template ' ,
36+ 'value ' => 'page-templates/template-widget.php '
37+ )
38+ )
39+ );
40+
41+ $ the_pages = new WP_Query ( $ args );
42+
43+ if ( $ the_pages ->have_posts () ) {
44+ foreach ( $ the_pages ->posts as $ post ) {
45+ $ this ->pages [ $ post ->post_name ] = array (
46+ 'id ' => $ post ->ID ,
47+ 'title ' => $ post ->post_title ,
48+ );
49+ $ this ->sidebars [] = 'shapely- ' . $ post ->post_name ;
50+ }
51+ }
52+
53+ }
54+
55+ public static function get_instance () {
56+ if ( is_null ( self ::$ instance ) ) {
57+ self ::$ instance = new self ();
58+ }
59+ return self ::$ instance ;
60+ }
61+
62+ public function register_sidebars () {
63+
64+ foreach ( $ this ->pages as $ slug => $ page ) {
65+ register_sidebar ( array (
66+ 'name ' => sprintf ( esc_html__ ( 'Page: %s ' , 'shapely ' ), $ page ['title ' ] ),
67+ 'id ' => 'shapely- ' . $ slug ,
68+ 'description ' => sprintf ( esc_html__ ( 'This widgets will appear in %s page ' , 'shapely ' ), $ page ['title ' ] ),
69+ 'before_widget ' => '<div id="%1$s" class="widget %2$s"> ' ,
70+ 'after_widget ' => '</div> ' ,
71+ 'before_title ' => '<h2 class="widget-title"> ' ,
72+ 'after_title ' => '</h2> ' ,
73+ ) );
74+ }
75+
76+ }
77+
78+ public function enqueue_builder_js () {
79+ $ builder_settings = array (
80+ 'siteURL ' => site_url (),
81+ 'pages ' => $ this ->pages ,
82+ );
83+ wp_enqueue_script ( 'shapely_builder_customizer ' , get_template_directory_uri () . '/assets/js/customizer-builder.js ' , array (), '20140317 ' , true );
84+
85+ wp_localize_script ( 'shapely_builder_customizer ' , 'ShapelyBuilder ' , $ builder_settings );
86+ }
87+
88+ public function remove_specific_widget ( $ sidebars_widgets ) {
89+
90+ foreach ( $ sidebars_widgets as $ widget_area => $ widget_list ) {
91+ if ( ! in_array ( $ widget_area , $ this ->sidebars ) && 'sidebar-home ' != $ widget_area ) {
92+ foreach ( $ widget_list as $ pos => $ widget_id ) {
93+ if ( strpos ( $ widget_id , 'shapely-page-content ' ) !== false || strpos ( $ widget_id , 'shapely-page-title ' ) !== false ) {
94+ unset( $ sidebars_widgets [ $ widget_area ][ $ pos ] );;
95+ }
96+ }
97+ }
98+ }
99+
100+ return $ sidebars_widgets ;
101+
102+ }
103+
104+ }
0 commit comments