Completed
Pull Request — master (#2)
by Luís
01:40
created

post-glue.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 24 and the first side effect is on line 18.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Plugin Name: Post Glue
4
 * Plugin URI: https://github.com/log-oscon/post-glue/
5
 * Description: Sticky posts for WordPress, improved.
6
 * Version: 1.0.0
7
 * Author: log.OSCON, Lda.
8
 * Author URI: https://log.pt/
9
 * License: GPL-2.0+
10
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
11
 * Text Domain: post-glue
12
 * Domain Path: /languages
13
 * GitHub Plugin URI: https://github.com/log-oscon/post-glue
14
 * GitHub Branch: master
15
 */
16
17
if ( ! defined( 'WPINC' ) ) {
18
	die;
19
}
20
21
/**
22
 * Implements plugin functionality.
23
 */
24
class Post_Glue {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
25
26
	/**
27
	 * Set sticky meta values on plugin activation.
28
	 */
29
	public static function activation() {
30
		self::stick_posts( get_option( 'sticky_posts', array() ) );
31
	}
32
33
	/**
34
	 * Initialize the plugin.
35
	 */
36
	public static function plugins_loaded() {
37
		$plugin_basename = plugin_basename( dirname( __FILE__ ) );
38
39
		load_plugin_textdomain( 'post-glue', false, $plugin_basename . '/languages' );
40
41
		add_action( 'admin_init', array( __CLASS__, 'admin_init' ) );
42
		add_action( 'update_option_sticky_posts', array( __CLASS__, 'update_option_sticky_posts' ), 10, 3 );
43
		add_action( 'pre_get_posts', array( __CLASS__, 'pre_get_posts' ) );
44
		add_filter( 'post_class', array( __CLASS__, 'post_class' ), 10, 3 );
45
	}
46
47
	/**
48
	 * Initialize the admin-specific parts of the plugin.
49
	 *
50
	 * Registers a Sticky metabox for every non-hierarchical post type and
51
	 * adds a view filter to the post edit screen.
52
	 */
53
	public static function admin_init() {
54
55
		// Get all public, non-hierarchical post types:
56
		$post_types = get_post_types( array( 'hierarchical' => false, 'public' => true ) );
57
58
		// Bypass the core post type:
59
		$post_types = array_diff( $post_types, array( 'post' ) );
60
61
		/**
62
		 * Filter the list of post types that support stickiness.
63
		 *
64
		 * Defaults to the list of public, non-hierarchical post types.
65
		 *
66
		 * @param array $post_types Post types that support stickiness.
67
		 */
68
		$post_types = apply_filters( 'post_glue_post_types', $post_types );
69
70
		add_meta_box(
71
			'post_glue_meta',
72
			__( 'Post Glue', 'post-glue' ),
73
			array( __CLASS__, 'admin_meta_box' ),
74
			$post_types,
75
			'side',
76
			'high'
77
		);
78
79
		foreach( $post_types as $post_type ) {
80
			add_filter( 'views_edit-' . $post_type, array( __CLASS__, 'views_edit' ) );
81
		}
82
	}
83
84
	/**
85
	 * Render the sticky meta box.
86
	 */
87
	public static function admin_meta_box() {
88
		?>
89
		<label for="post-glue-sticky" class="selectit">
90
			<input id="post-glue-sticky" name="sticky" type="checkbox"
91
				value="sticky" <?php checked( is_sticky() ) ?>>
92
			<?php _e( 'Make this post sticky', 'post-glue' ) ?>
93
		</label>
94
		<?php
95
	}
96
97
	/**
98
	 * Add sticky post view to the post edit page in the admin.
99
	 *
100
	 * @param  array $views Admin post edit views.
101
	 * @return array        Filtered admin post edit views.
102
	 */
103
	public static function views_edit( $views ) {
104
		global $wp_query;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
105
106
		$post_type    = $wp_query->get( 'post_type' );
107
		$sticky_posts = array();
108
109
		foreach( get_option( 'sticky_posts', array() ) as $post_id ) {
110
			if ( get_post_type( $post_id ) === $post_type ) {
111
				$sticky_posts[] = $post_id;
112
			}
113
		}
114
115
		$sticky_posts_count = count( $sticky_posts );
116
117
		if ( ! $sticky_posts_count ) {
118
			return $views;
119
		}
120
121
		$sticky_inner_html = sprintf(
122
			_nx(
123
				'Sticky <span class="count">(%s)</span>',
124
				'Sticky <span class="count">(%s)</span>',
125
				$sticky_posts_count,
126
				'post-glue'
127
			),
128
			number_format_i18n( $sticky_posts_count )
129
		);
130
131
		$views['sticky'] = sprintf(
132
			'<a href="%sedit.php?post_type=%s&show_sticky=1">%s</a>',
133
			get_admin_url(),
134
			$post_type,
135
			$sticky_inner_html
136
		);
137
138
		return $views;
139
	}
140
141
	/**
142
	 * Saves post stickiness to the `_sticky` post meta key.
143
	 *
144
	 * @param  mixed  $old_value Previous option value.
145
	 * @param  mixed  $value     New option value.
146
	 * @param  string $option    Option name.
147
	 */
148
	public static function update_option_sticky_posts( $old_value, $value, $option ) {
0 ignored issues
show
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
149
		$added   = array_diff( $value, $old_value );
150
		$removed = array_diff( $old_value, $value );
151
152
		self::stick_posts( $added );
153
		self::unstick_posts( $removed );
154
	}
155
156
	/**
157
	 * Sort posts by stickiness.
158
	 *
159
	 * Changes queries to include sticky posts on the default sort order.
160
	 * Honours the `ignore_sticky_posts` query argument.
161
	 *
162
	 * The meta query added by this action translates to a `LEFT JOIN` where the
163
	 * `_sticky` meta key is checked for both existence and non-existence. The
164
	 * point is to force the WordPress SQL builder to perform a `CAST(meta_value
165
	 * AS SIGNED)` in the `ORDER BY` clause as a sort of poor man's `COALESCE()`.
166
	 *
167
	 * @param WP_Query $query The current query instance, passed by reference.
168
	 */
169
	public static function pre_get_posts( $query ) {
170
171
		// Don't alter admin queries:
172
		if ( is_admin() ) {
173
			return;
174
		}
175
176
		// Ignore sticky posts:
177
		if ( $query->get( 'ignore_sticky_posts' ) ) {
178
			return;
179
		}
180
181
		// Don't show stickies outside of home, post type or taxonomy archives:
182
		if ( ! $query->is_home() && ! $query->is_post_type_archive() && ! $query->is_tax() ) {
183
			return;
184
		}
185
186
		// Ignore queries that already provide an order:
187
		if ( $query->get( 'orderby' ) ) {
188
			return;
189
		}
190
191
		// Ignore queries that already provide a meta query:
192
		if ( $query->get( 'meta_query' ) ) {
193
			return;
194
		}
195
196
		// Ignore core stickies now:
197
		$query->set( 'ignore_sticky_posts', 1 );
198
199
		$query->set( 'meta_query', array(
200
			array(
201
				'relation' => 'OR',
202
				array(
203
					'key'     => '_sticky',
204
					'type'    => 'BINARY',
205
					'compare' => 'EXISTS',
206
				),
207
				'sticky_clause' => array(
208
					'key'     => '_sticky',
209
					'type'    => 'BINARY',
210
					'compare' => 'NOT EXISTS',
211
				),
212
			),
213
		) );
214
215
		$query->set( 'orderby', array(
216
			'sticky_clause' => 'DESC',
217
			'date'          => 'DESC',
218
		) );
219
	}
220
221
	/**
222
	 * Add a `sticky` HTML class to posts.
223
	 *
224
	 * @param  array  $classes  An array of post classes.
225
	 * @param  array  $class    An array of additional classes added to the post.
226
	 * @param  int    $post_id  The post ID.
227
	 * @return array            Filtered class list.
228
	 */
229
	public static function post_class( $classes, $class, $post_id ) {
230
		if ( is_sticky( $post_id ) ) {
231
			if ( is_home() || is_post_type_archive() || is_tax() ) {
232
				$classes[] = 'sticky';
233
			}
234
		}
235
236
		return $classes;
237
	}
238
239
	/**
240
	 * Bulk update _sticky meta values for a group of post IDs.
241
	 *
242
	 * @param  array  $posts List of post IDs.
243
	 */
244
	private static function stick_posts( $posts ) {
245
		foreach ( $posts as $post_id ) {
246
			update_post_meta( $post_id, '_sticky', 1 );
247
		}
248
	}
249
250
	/**
251
	 * Bulk delete _sticky meta values for a group of post IDs.
252
	 *
253
	 * @param  array  $posts List of post IDs.
254
	 */
255
	private static function unstick_posts( $posts ) {
256
		foreach ( $posts as $post_id ) {
257
			delete_post_meta( $post_id, '_sticky' );
258
		}
259
	}
260
261
}
262
263
register_activation_hook( __FILE__, array( 'Post_Glue', 'activation' ) );
264
265
add_action( 'plugins_loaded', array( 'Post_Glue', 'plugins_loaded' ) );
266