WP_Query mit "post_title LIKE 'Something%'"?
5 Antworten
- Stimmen
-
- 2011-05-30
Ich würde diesmit einem Filterfür
WP_Query
lösen.Eine,dieeine zusätzliche Abfragevariableerkennt und diese als Präfix des Titels verwendet.add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 ); function wpse18703_posts_where( $where, &$wp_query ) { global $wpdb; if ( $wpse18703_title = $wp_query->get( 'wpse18703_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( $wpdb->esc_like( $wpse18703_title ) ) . '%\''; } return $where; }
Auf diese Weise können Sieimmernoch
WP_Query
aufrufen. Sie übergeben den Titeleinfach alswpse18703_title
-Argument (oder ändern den Namenin etwas kürzeres).I would solve this with a filter on
WP_Query
. One that detects an extra query variable and uses that as the prefix of the title.add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 ); function wpse18703_posts_where( $where, &$wp_query ) { global $wpdb; if ( $wpse18703_title = $wp_query->get( 'wpse18703_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( $wpdb->esc_like( $wpse18703_title ) ) . '%\''; } return $where; }
This way you can still call
WP_Query
, you just pass the title as thewpse18703_title
argument (or change the name to something shorter).-
Diesemfehltirgendwie das `$ wpdb->prepare ()`.This one is somehow missing the `$wpdb->prepare()`.
- 1
- 2012-11-06
- kaiser
-
@kaiser: Esist lange her,aberich denke,das warmit `prepare ()`nichtmöglich.$ wpdb->prepare ('LIKE "% s %%"','banana') `würde" LIKE ''banana '%' "zurückgeben,alsomüssen wir die Abfrage selbsterstellen und auch die Escape-Funktion ausführen.@kaiser: It's been a long time, but I think this was not possible with `prepare()`. `$wpdb->prepare('LIKE "%s%%"', 'banana')` would return `"LIKE ''banana'%'"`, so we have to construct the query ourselves, and do the escaping too.
- 0
- 2012-11-06
- Jan Fabry
-
@ JanFabry Schön dich wieder zu sehen!:) Kommmalim Chat vorbei,hm?StopPress würde sichfreuen,Sie zu sehen.Über das `prepare ()`.Ja,dasist schwierig undichmussteesmehrmals versuchen,bevoriches umgehen konnte.Ausetwas,dasichgeradegemacht habe: `$ wpdb->prepare ('AND {$ wpdb->posts} .post_title LIKE% s',esc_sql ('%'. Like_escape (trim ($term)). '%'))`.Undichbin mir ziemlich sicher,dass "esc_sql ()" unnötig undnurparanoidist.@JanFabry Happy to see you agaaaaaaaain! :) Drop by in chat some time, hm? StopPress would be happy to see you. About that `prepare()`. Yeah, that's tricky and I had to try that several times, before I got around it. From something I just made: `$wpdb->prepare( ' AND {$wpdb->posts}.post_title LIKE %s ', esc_sql( '%'.like_escape( trim( $term ) ).'%' ) )`. And I'm pretty sure the `esc_sql()` is unnecessary and just paranoid.
- 1
- 2012-11-07
- kaiser
-
Es scheint,dass Sie keine Zeichenfolgemit "" (Apostroph) darin suchen können.Ich denke,es liegt an der Flucht?Ich habe die LösungnochnichtgefundenIt seems that you can't search a string with `'` (apostrophe) inside. I guess it's because of escaping ? I didn't find the solution yet
- 0
- 2018-08-30
- Vincent Decaux
-
- 2013-04-19
Vereinfacht:
function title_filter( $where, &$wp_query ) { global $wpdb; // 2. pull the custom query in here: if ( $search_term = $wp_query->get( 'search_prod_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\''; } return $where; } $args = array( 'post_type' => 'product', 'posts_per_page' => $page_size, 'paged' => $page, // 1. define a custom query var here to pass your term through: 'search_prod_title' => $search_term, 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ); add_filter( 'posts_where', 'title_filter', 10, 2 ); $wp_query = new WP_Query($args); remove_filter( 'posts_where', 'title_filter', 10 ); return $wp_query;
Simplified:
function title_filter( $where, &$wp_query ) { global $wpdb; // 2. pull the custom query in here: if ( $search_term = $wp_query->get( 'search_prod_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\''; } return $where; } $args = array( 'post_type' => 'product', 'posts_per_page' => $page_size, 'paged' => $page, // 1. define a custom query var here to pass your term through: 'search_prod_title' => $search_term, 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ); add_filter( 'posts_where', 'title_filter', 10, 2 ); $wp_query = new WP_Query($args); remove_filter( 'posts_where', 'title_filter', 10 ); return $wp_query;
-
Bittefügen Sie Ihrem Codeeine Erklärungbei.Please include an explanation along with your code.
- 13
- 2013-04-19
- s_ha_dum
-
Große VereinfachungGreat simplification
- 2
- 2014-11-10
- Timo Huovinen
-
Codeistmeiner Meinungnach selbsterklärend,zumindestfürmich.Vielen Dankfür das Teilen des vollständigen Skripts.Code is i think self explained, atleast for me. Thanks for sharing complete script.
- 2
- 2017-08-08
- Hassan Dad Khan
-
Verwenden Sie '$ wpdb->esc_like (' anstelle von 'esc_sql (like_escape ('))Use '$wpdb->esc_like (' instead of 'esc_sql( like_escape('
- 2
- 2018-02-19
- fdrv
-
@fdrv Sie haben Recht,aber laut wp docsbenötigen $ wpdb->esc_likeimmernochesc_sql ().Ich denke also,der richtige Code wäreesc_sql ($ wpdb->esc_like ($ search_term))@fdrv You are right but according to wp docs $wpdb->esc_like still need esc_sql(). So I think the correct code would be esc_sql( $wpdb->esc_like( $search_term ) )
- 0
- 2019-10-18
- Waqas Bukhary
-
`like_escape` veraltet 4.0.0 Verwenden Sie` wpdb ::esc_like``like_escape` deprecated 4.0.0 Use `wpdb::esc_like`
- 0
- 2020-03-14
- Empty Brain
-
`remove_filter` verwendetnur 3 Argumente,das letzte kannentfernt werden.`remove_filter` only uses 3 arguments, the last one can be removed.
- 2
- 2020-06-24
- Skatox
-
- 2015-01-02
Wollte diesen Code aktualisieren,an demihrfür WordPress 4.0 und höhergearbeitet habt,daesc_sql ()in 4.0 höher veraltetist.
function title_filter($where, &$wp_query){ global $wpdb; if($search_term = $wp_query->get( 'search_prod_title' )){ /*using the esc_like() in here instead of other esc_sql()*/ $search_term = $wpdb->esc_like($search_term); $search_term = ' \'%' . $search_term . '%\''; $where .= ' AND ' . $wpdb->posts . '.post_title LIKE '.$search_term; } return $where; }
Der Restistgleich.
Außerdemmöchteich darauf hinweisen,dass Sie die Variable s in WP_Query-Argumenten verwenden können,um Suchbegriffe zu übergeben,diemeiner Meinungnach auchnach dem Post-Titel suchen.
So:
$args = array( 'post_type' => 'post', 's' => $search_term, 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ); $wp_query = new WP_Query($args);
Wanted to update this code you guys worked on for the wordpress 4.0 and above as esc_sql() is deprecated in 4.0 higher.
function title_filter($where, &$wp_query){ global $wpdb; if($search_term = $wp_query->get( 'search_prod_title' )){ /*using the esc_like() in here instead of other esc_sql()*/ $search_term = $wpdb->esc_like($search_term); $search_term = ' \'%' . $search_term . '%\''; $where .= ' AND ' . $wpdb->posts . '.post_title LIKE '.$search_term; } return $where; }
Rest of the stuff is same.
Also I want to point out you can use s variable within WP_Query arguments to pass search terms, which will also search for post title i believe.
Like this:
$args = array( 'post_type' => 'post', 's' => $search_term, 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ); $wp_query = new WP_Query($args);
-
Wasgenauist "search_prod_title"?Sollich dasin etwas anderes ändern?What exactly `search_prod_title` is? Should i change this to something else?
- 0
- 2017-03-24
- Antonios Tsimourtos
-
Seit wann wird `esc_sql`beraubt?Esistnicht.`$ wpdb-> Escape`ist allerdings ... https://developer.wordpress.org/reference/functions/esc_sql/Since when is `esc_sql` depricated? It's not. `$wpdb->escape` is though... https://developer.wordpress.org/reference/functions/esc_sql/
- 0
- 2018-02-02
- Jeremy
-
Beachten Sie,dass der Parameter s auch den Inhalt des Beitrags durchsucht,wasmöglicherweisenicht dasgewünschte Zielist.=)Note that the s parameter searches the post content as well, which may not be the desired aim. =)
- 1
- 2018-04-19
- Christine Cooper
-
`like_escape` veraltet` 4.0.0` Verwenden Sie` wpdb ::esc_like``like_escape` deprecated `4.0.0` Use `wpdb::esc_like`
- 0
- 2020-03-14
- Empty Brain
-
- 2018-04-19
Miteiner anfälligen Lösung,die hier veröffentlicht wurde,habeicheine etwas vereinfachte undbereinigte Version.
Zuersterstellen wireine Funktionfür den Filter
posts_where
,mit der Sienur Posts anzeigen können,diebestimmten Bedingungenentsprechen:function cc_post_title_filter($where, &$wp_query) { global $wpdb; if ( $search_term = $wp_query->get( 'cc_search_post_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . $wpdb->esc_like( $search_term ) . '%\''; } return $where; }
Jetztfügen wir
cc_search_post_title
zu unseren Abfrageargumenten hinzu:$args = array( 'cc_search_post_title' => $search_term, // search post title only 'post_status' => 'publish', );
Und wickeln Sie den Filter schließlich um die Abfrage:
add_filter( 'posts_where', 'cc_post_title_filter', 10, 2 ); $query = new WP_Query($args); remove_filter( 'posts_where', 'cc_post_title_filter', 10 );
Verwenden vonget_posts ()
Bestimmte Funktionen,die Beiträge abrufen,führen keine Filter aus,sodass die angehängten Filterfunktionenposts_where die Abfragenicht ändern. Wenn Sie vorhaben,
get_posts()
zum Abfragen Ihrer Posts zu verwenden,müssen Siesuppress_filters
in Ihrem Argumentarray auffalse setzen:$args = array( 'cc_search_post_title' => $search_term, 'suppress_filters' => FALSE, 'post_status' => 'publish', );
Jetzt können Sie
get_posts()
verwenden:add_filter( 'posts_where', 'cc_post_title_filter', 10, 2 ); $posts = get_posts($args); remove_filter( 'posts_where', 'cc_post_title_filter', 10 );
Wasistmit dem Parameter
s
?Der Parameter
s
ist verfügbar:$args = array( 's' => $search_term, );
Während Sie Ihren Suchbegriffin den Parameter
s
einfügen und den Titel des Beitrags durchsuchen,wird auch der Inhalt des Beitrags durchsucht.Wasistmit dem Parameter
title
,dermit WP 4.4 hinzugefügt wurde?Übergebeneines Suchbegriffs an den Parameter
title
:$args = array( 'title' => $search_term, );
unterscheidet zwischen Groß- und Kleinschreibung und
LIKE
,nicht%LIKE%
. Diesemittlere Suchenachhello
gibt keinen Beitragmit dem TitelHello World
oderhello
zurück.With some vulnerable solution posted here, I come with a bit simplified and sanitized version.
First, we create a function for the
posts_where
filter which allows you to only show posts matching specific conditions:function cc_post_title_filter($where, &$wp_query) { global $wpdb; if ( $search_term = $wp_query->get( 'cc_search_post_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . $wpdb->esc_like( $search_term ) . '%\''; } return $where; }
Now we add
cc_search_post_title
into our query arguments:$args = array( 'cc_search_post_title' => $search_term, // search post title only 'post_status' => 'publish', );
And finally wrap the filter around the query:
add_filter( 'posts_where', 'cc_post_title_filter', 10, 2 ); $query = new WP_Query($args); remove_filter( 'posts_where', 'cc_post_title_filter', 10 );
Using get_posts()
Certain functions which retrieve posts do not run filters, so the posts_where filter functions you attach will not modify the query. If you plan to use
get_posts()
to query your posts, you need to setsuppress_filters
to false in your argument array:$args = array( 'cc_search_post_title' => $search_term, 'suppress_filters' => FALSE, 'post_status' => 'publish', );
Now you can use
get_posts()
:add_filter( 'posts_where', 'cc_post_title_filter', 10, 2 ); $posts = get_posts($args); remove_filter( 'posts_where', 'cc_post_title_filter', 10 );
What about the
s
parameter?The
s
parameter is available:$args = array( 's' => $search_term, );
While adding your search term into the
s
parameter work and it will search the post title, it will also search the post content.What about the
title
parameter which was added with WP 4.4?Passing a search term into the
title
parameter:$args = array( 'title' => $search_term, );
Is case sensitive and
LIKE
, not%LIKE%
. This mean search forhello
will not return post with titleHello World
orHello
.-
Ausgezeichnet.Ich habenach 'post_title' als Parametergesucht und offensichtlichnichtsgefunden.Excellent. I was looking for 'post_title' as a parameter and, obviously, didn't find anything.
- 0
- 2019-09-13
- MastaBaba
-
Icherhalteeine Fehlermeldungbei der wp-Abfrage odererhalte Beiträge: "E_WARNING Fehlerin der Datei» class-wp-hook.php «in Zeile 288: Parameter 2bis cc_post_title_filter () wird als Referenzerwartet,Wert angegebenI'm getting an error with wp query or get posts: "E_WARNING Error in file »class-wp-hook.php« at line 288: Parameter 2 to cc_post_title_filter() expected to be a reference, value given
- 0
- 2020-03-03
- Elkrat
-
@Elkrat Entfernen Sie das "&" aus "& $ wp_query"in "cc_post_title_filter".@Elkrat Remove the `&` from `&$wp_query` in `cc_post_title_filter`.
- 0
- 2020-05-05
- Mattimator
-
- 2015-04-28
Aufbauend auf anderen Antworten vormir,um Flexibilitätin der Situation zubieten,in der Sieeinen Beitrag suchenmöchten,derein Wortin einem Metafeld ODERim Titel des Beitragsenthält,gebe ich diese Option über das Argument "title_filter_relation". In dieser Implementierungerlaubeichnur "ODER" - oder "UND" -Eingabenmit der Standardeinstellung "UND".
function title_filter($where, &$wp_query){ global $wpdb; if($search_term = $wp_query->get( 'title_filter' )){ $search_term = $wpdb->esc_like($search_term); //instead of esc_sql() $search_term = ' \'%' . $search_term . '%\''; $title_filter_relation = (strtoupper($wp_query->get( 'title_filter_relation'))=='OR' ? 'OR' : 'AND'); $where .= ' '.$title_filter_relation.' ' . $wpdb->posts . '.post_title LIKE '.$search_term; } return $where; }
Hieristein Beispielfür den Codein Aktionfüreinen sehreinfachen Beitragstyp "faq",bei dem die Frage der Beitragstitel selbstist:
add_filter('posts_where','title_filter',10,2); $s1 = new WP_Query( array( 'post_type' => 'faq', 'posts_per_page' => -1, 'title_filter' => $q, 'title_filter_relation' => 'OR', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'faq_answer', 'value' => $q, 'compare' => 'LIKE' ) ) )); remove_filter('posts_where','title_filter',10,2);
Building on other answers before me, to provide flexibility in the situation where you want to search a post that contains a word in a meta field OR in the title of the post, I give that option via the argument "title_filter_relation." In this implementation, I only allow for "OR" or "AND" inputs with a default of "AND."
function title_filter($where, &$wp_query){ global $wpdb; if($search_term = $wp_query->get( 'title_filter' )){ $search_term = $wpdb->esc_like($search_term); //instead of esc_sql() $search_term = ' \'%' . $search_term . '%\''; $title_filter_relation = (strtoupper($wp_query->get( 'title_filter_relation'))=='OR' ? 'OR' : 'AND'); $where .= ' '.$title_filter_relation.' ' . $wpdb->posts . '.post_title LIKE '.$search_term; } return $where; }
Here's an example of the code in action for a very simple post type "faq" where the question is the post title itself:
add_filter('posts_where','title_filter',10,2); $s1 = new WP_Query( array( 'post_type' => 'faq', 'posts_per_page' => -1, 'title_filter' => $q, 'title_filter_relation' => 'OR', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'faq_answer', 'value' => $q, 'compare' => 'LIKE' ) ) )); remove_filter('posts_where','title_filter',10,2);
-
Gute Einsicht,Hinzufügen vonbenutzerdefinierten "Abfragevariablen" zu den an "WP_Query" übergebenen Abfrageargumenten,umim Filter "posts_where" darauf zugreifen zu können.Good insight, adding custom "query vars" to the query args passed to `WP_Query` in order to be able to access them within the `posts_where` filter.
- 1
- 2017-02-04
- Tom Auger
Ichmusseine
WP_Query
mit einemLIKE
auf dempost_title
ausführen.Ich habemit diesem regulären
WP_Query
begonnen:Aber wasicheigentlichmachenmöchte,siehtin SQL so aus:
Die Ausgabegibt die Ergebnisse aus,dieicherwarte,aberich verwende den regulären
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
,um die Ergebnisse anzuzeigen.Und dasfunktioniertnichtmit
$wpdb->get_results()
.Wie kannich daserreichen,wasich hierbeschrieben habe?