I am having problems when querying a WP_Query Object when a user has a role different than administrator
My WP_Query is this:
function remove_new_c_post($author_id,$value_id) {
$query = new WP_Query( array(
'post_type' => 'custom_post_type',
'author' => $author_id,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'value_id',
'value' => $value_id,
'compare' => 'LIKE',
),
),
'order' => 'ASC'
));
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
wp_delete_post( get_the_ID() );
endwhile;
wp_reset_postdata();
endif;
}
For some reason when the query is run by a user other than the administrator, this is the result:
WP_Query Object
(
[query] => Array
(
[post_type] => custom_post_type
=> 70
[meta_query] => Array
(
[relation] => AND
[0] => Array
(
[key] => value_id
[value] => 86
[compare] => LIKE
)
)
[order] => ASC
)
[query_vars] => Array
(
[post_type] => custom_post_type
=> 86 //<--- THIS SHOULD BE 70
[meta_query] => Array
(
[relation] => AND
[0] => Array
(
[key] => value_id
[value] => 86
[compare] => LIKE
)
)
[order] => ASC
...
Please notice the author in query_vars
it is 86 when it should be 70. Why is this being altered?
EDIT:
I just tried to set the query_var $query->set( 'author', $author_id );
and it kept the author_id intact; howevever, the mysql keeps getting altered:
[request] => SELECT SQL_CALC_FOUND_ROWS dlwp_posts.ID
FROM dlwp_posts
INNER JOIN dlwp_postmeta ON ( dlwp_posts.ID = dlwp_postmeta.post_id )
WHERE 1=1 AND dlwp_posts.post_author IN (86)
AND dlwp_posts.post_type="custom_post_type"
AND (dlwp_posts.post_status="publish"
OR dlwp_posts.post_status="future"
OR dlwp_posts.post_status="draft"
OR dlwp_posts.post_status="pending"
OR dlwp_posts.post_status="private")
AND (( dlwp_postmeta.meta_key = 'value_id'
AND CAST(dlwp_postmeta.meta_value AS CHAR) LIKE '%86%' )
1 Answer
Milo’s comment about pre_get_posts
helped solve this issue for me. In my case the parent theme used the pre_get_posts
action to explicitly set the post_type
for all author pages. It wasn’t in the functions.php, but I was able to find it by searching the theme for instances of pre_get_posts
. (I used grep -R "pre_get_posts" . -l
from the command line to find the file.)
If you’re not using a child theme, you could potentially just delete the problematic function and its add_action()
.
If you are using a child theme, to maintain upgradability of the parent theme, you can use the remove_action function…
Problematic Action existing in Parent Theme:
function problematic_parent_action( &$query ) {
if ($query->is_author) {
$query->set( 'post_type', array( 'problematic_parent_post_type' ) );
}
}
add_action( 'pre_get_posts', 'problematic_parent_action' );
Resolution added to Child Theme:
function remove_problematic_parent_action() {
remove_action( 'pre_get_posts', 'problematic_parent_action' );
}
add_action( 'init', 'remove_problematic_parent_action');