首页 > 解决方案 > Trouble with apostrophes in Wordpress meta_query

问题描述

I've seen this issue around but I can't seem to find the solution that works for me. I am trying to filter posts based on the article_tag and all of them work except for the one with an apostrophe in it.

Here is my code for the select:

<select name='tagFilter'>
    <option value="Lead" <?php echo display_selected($tag, "Lead Story");?>>Lead Story</option>
    <option value="Executive Corner" <?php echo display_selected($tag, "Executive Corner");?>>Executive Corner</option>
    <option value="Executive Highlight" <?php echo display_selected($tag, "Executive Highlight");?>>Executive Highlight</option>
    <option value="What's New" <?php echo display_selected($tag, "What's New");?>>What's New</option>
</select>

I set the $tag variable like this:

$tag='';

if( !empty( $_GET['tagFilter'])){
    $tag = $_GET['tagFilter'];
}

And this is my query:

$tag_query = array('relation' => 'AND');
if(!empty($tag)){
    array_push($tag_query, array(
        'key' => 'article_type',
        'value' => $tag,
        'compare' => '='
    ));
}   

$filter_query_args = array(
    'post_type' => 'vbc_news_blog',
    'post_status' => 'published',
    'orderby' => 'date',
    'paged' => $paged,
    'date_query' => $date_query,
    'meta_query' => $tag_query
);

$filterQuery = new WP_Query( $filter_query_args );

I've tried addslashes and stripslashes (I don't really know how those work I just saw those solutions when looking around) but those didn't do anything. Anyone have any advice?

标签: phpwordpress

解决方案


我认为您正在寻找sanitize_text_field( string $str )wordpress 的功能。

function sanitize_text_field( $str ) {
    $filtered = _sanitize_text_fields( $str, false );

    /**
     * Filters a sanitized text field string.
     *
     * @since 2.9.0
     *
     * @param string $filtered The sanitized string.
     * @param string $str      The string prior to being sanitized.
     */
    return apply_filters( 'sanitize_text_field', $filtered, $str );
}

这是文档的链接,https://developer.wordpress.org/reference/functions/sanitize_text_field/


推荐阅读