Support » Alpha/Beta/RC » Prepare function removes percent signs from LIKE SQL statement

  • Resolved AlanP57

    (@alanp57)


    My plugin use a LIKE SQL statement and with RC3 the percent signs are removed from the SQL resulting in the query no longer working.
    $wpdb->prepare(“select * from wp_posts where post_title LIKE ‘%%%s%%'”, “news”);
    should result in “select * from wp_posts where post_title LIKE ‘%news%'”. Instead it outputs “select * from wp_posts where post_title LIKE ‘news'” and thus fails.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Do you really write in your source code

    $wpdb->prepare("select * from wp_posts where post_title LIKE '%%%s%%'", "news");

    ? I would recommend another, safer way for what you want to achieve:

    add_filter( 'posts_where', 'extend_wp_query_where', 10, 2 );
    function extend_wp_query_where( $where, $wp_query ) {
    	if ( $extend_where = $wp_query->get( 'extend_where' ) ) {
    		$where .= " AND " . $extend_where;
    	}
    	return $where;
    }
    $query = [
            'post_status' => 'any',
    	'extend_where' => "(post_title like '%news%')"
    ];
    $results = new WP_Query( $query );

    This also works for me in the latest RC5 for WordPress 6.1.

    Thread Starter AlanP57

    (@alanp57)

    Unfortunately I’m not using a LIKE in a WordPress post loop and thus this explanation would not apply.

    Let me revise my question. The issue I am having is not with the absence of the percent signs, it is with the insertion of extra quote marks around like search text. In WordPress 6.0.3 my SQL query works and the output is like this:

    like '{31251fed5c2403d79bc9ccae064144d17b9b065f8a3b4b135b3b66b890f40e49}my search text{31251fed5c2403d79bc9ccae064144d17b9b065f8a3b4b135b3b66b890f40e49}'

    But in 6.1 RC3 the same code fails because of this output:

    like '{ded25e87046de06e690f2947178715c5a033eff849ae0c87637217f18a53b172}'my search text'{ded25e87046de06e690f2947178715c5a033eff849ae0c87637217f18a53b172}'

    • This reply was modified 4 weeks, 1 day ago by AlanP57.

    I just have the suspicion you have encountered the bug here: https://core.trac.wordpress.org/ticket/56802 – current is RC5, have you tried it with it? Otherwise I would recommend you to report your problem (with RC5 as base) in the core track so the developers can have a look at it.

    Thread Starter AlanP57

    (@alanp57)

    This issue has been resolved in 6.1 RC6. https://core.trac.wordpress.org/ticket/56933

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.