class-recalculate-scores-ajax.php
2.59 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* @package WPSEO\Admin|Ajax
*/
/**
* Class WPSEO_Recalculate_Scores
*
* This class handles the SEO score recalculation for all posts with a filled focus keyword
*/
class WPSEO_Recalculate_Scores_Ajax {
/**
* Initialize the AJAX hooks
*/
public function __construct() {
add_action( 'wp_ajax_wpseo_recalculate_scores', array( $this, 'recalculate_scores' ) );
add_action( 'wp_ajax_wpseo_update_score', array( $this, 'save_score' ) );
add_action( 'wp_ajax_wpseo_recalculate_total', array( $this, 'get_total' ) );
}
/**
* Get the totals for the posts and the terms.
*/
public function get_total() {
check_ajax_referer( 'wpseo_recalculate', 'nonce' );
wp_die(
wp_json_encode(
array(
'posts' => $this->calculate_posts(),
'terms' => $this->calculate_terms(),
)
)
);
}
/**
* Start recalculation
*/
public function recalculate_scores() {
check_ajax_referer( 'wpseo_recalculate', 'nonce' );
$fetch_object = $this->get_fetch_object();
if ( ! empty( $fetch_object ) ) {
$paged = filter_input( INPUT_POST, 'paged', FILTER_VALIDATE_INT );
$response = $fetch_object->get_items_to_recalculate( $paged );
if ( ! empty( $response ) ) {
wp_die( wp_json_encode( $response ) );
}
}
wp_die( '' );
}
/**
* Saves the new linkdex score for given post
*/
public function save_score() {
check_ajax_referer( 'wpseo_recalculate', 'nonce' );
$fetch_object = $this->get_fetch_object();
if ( ! empty( $fetch_object ) ) {
$scores = filter_input( INPUT_POST, 'scores', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );
$fetch_object->save_scores( $scores );
}
wp_die();
}
/**
* Returns the needed object for recalculating scores.
*
* @return WPSEO_Recalculate_Posts|WPSEO_Recalculate_Terms
*/
private function get_fetch_object() {
switch ( filter_input( INPUT_POST, 'type' ) ) {
case 'post':
return new WPSEO_Recalculate_Posts();
case 'term':
return new WPSEO_Recalculate_Terms();
}
return null;
}
/**
* Gets the total number of posts
*
* @return int
*/
private function calculate_posts() {
$count_posts_query = new WP_Query(
array(
'post_type' => 'any',
'meta_key' => '_yoast_wpseo_focuskw',
'posts_per_page' => 1,
'fields' => 'ids',
)
);
return $count_posts_query->found_posts;
}
/**
* Get the total number of terms
*
* @return int
*/
private function calculate_terms() {
$total = 0;
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
$total += wp_count_terms( $taxonomy->name, array( 'hide_empty' => false ) );
}
return $total;
}
}