What I am attempting to do is sort posts by custom fields.
I have a few custom fields that don’t query properly and I get the 404 page. The fields that don’t work I used hyphens in the naming convention, i.e. var-name
. When I switch the hyphens to underscores it works, i.e. var_name
.
Am I overlooking something simple in PHP or WordPress that causes conflicts when I do this?
- I know I could simply just switch everything to underscores but I like to know the root of issues so I can avoid them in the future.
I am using pre_get_posts
to modify the query being executed:
add_action( 'pre_get_posts', 'my_modify_query' );
function my_modify_query( $wp_query ) {
if ( is_category() ) {
// Works - underscore
if ( isset( $_REQUEST['var_name'] ) ) {
$meta_query[] = array( 'key' => 'var_name', 'value' => $_REQUEST['var_name'] );
}
// Sometimes works - hyphen
if ( isset( $_REQUEST['var-name'] ) ) {
$meta_query[] = array( 'key' => 'var-name', 'value' => $_REQUEST['var-name'] );
}
if ( ! empty( $meta_query ) ) {
$wp_query->set( 'meta_query', $meta_query );
}
}
}
Have additional custom fields I check for, the above example is for brevity and clarification and is the same for additional fields.
EDIT 1
Here are the queries being run by WordPress:
The unsuccessful hyphen
SELECT SQL_CALC_FOUND_ROWS wp_xxxxx_posts.ID
FROM wp_xxxxx_posts
WHERE 1=1
AND 0 = 1
AND wp_xxxxx_posts.post_type IN ('post')
AND (
wp_xxxxx_posts.post_status="publish"
OR
wp_xxxxx_posts.post_author = 1
AND
wp_xxxxx_posts.post_status="private")
GROUP BY wp_xxxxx_posts.ID
ORDER BY wp_xxxxx_posts.post_date DESC
LIMIT 0, 10
The successful underscore
SELECT SQL_CALC_FOUND_ROWS wp_xxxxx_posts.ID
FROM wp_xxxxx_posts
INNER JOIN wp_j9L3vi_postmeta ON (wp_xxxxx_posts.ID = wp_xxxxx_postmeta.post_id)
WHERE 1=1
AND wp_xxxxx_posts.post_type IN ('post', 'custom_post_type' )
AND (
wp_xxxxx_posts.post_status="publish"
OR
wp_xxxxx_posts.post_author = 1 AND wp_xxxxx_posts.post_status="private"
)
AND ( (
wp_xxxxx_postmeta.meta_key = 'var_name'
AND CAST(wp_xxxxx_postmeta.meta_value AS CHAR) = '116'
) )
GROUP BY wp_xxxxx_posts.ID
ORDER BY wp_xxxxx_posts.post_date DESC
LIMIT 0, 10
If I go into phpMyAdmin and simply switch out var_name
in the above query to var-name
it works.
Edit 2
I am passing the custom fields as so:
http://mysite.com/?cat=example&var-name=100