I have this query that works fine:
$query = new WP_Query(array( 's' => $keyword ,'post_status' => array('publish', 'pending', 'draft')) );
Its searches and finds the post with the keyword in title.
I want to query posts with a few keywords at once, (Now i'm doing a loop over all keywords and query each keyword by itself.
If it was mysql it would have be something like:
Select * from ..... where title='keyword1' or title='keyword2' or title='keyword3' ;
How could achieve that with WP_Query?
You can't do it using the WP_Query directly.
An alternative for looping the WP_Query is use the $wpdb.
$wpdb->get_row( "SELECT * FROM $wpdb->posts WHERE where title='keyword1' or title='keyword2' or title='keyword3'" );
U have to use $wpdb (#codex)
$query= $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM ....
WHERE title= %s OR
title=%s OR
title = %s
",
$keyword1,
$keyword2,
$keyword3
) );
I hope that help u:)
Related
i am working with wordpress,And i want to pass one parameter name "post_title" in wp_query,So i can change query and can get correct data,But my query is not changed(not displaying as i expected),I tried with following code
$args = array(
'post_type' => 'user',
'posts_per_page' => -1,
'post_title' => $_GET['post_title'],
'post_status' => [ 'publish']
);
$query = new WP_Query($args);
when i print my $query->request then i getting following query
[request] = "SELECT MZAGsQVeposts.* FROM MZAGsQVeposts WHERE 1=1 AND MZAGsQVeposts.post_type = 'user' AND ((MZAGsQVeposts.post_status = 'publish')) ORDER BY MZAGsQVeposts.post_date DESC";
But expected query is
"SELECT MZAGsQVeposts.* FROM MZAGsQVeposts WHERE 1=1 AND MZAGsQVeposts.post_type = 'user' AND ((MZAGsQVeposts.post_status = 'publish')) AND MZAGsQVeposts.post_title='Lisa I' ORDER BY MZAGsQVeposts.post_date DESC";
Where i am wrong ? Thanks in advance.
Unfortunately you can't query posts by title in wp_query, it's not a recognised argument. (See WP_Query for more info) however you can use get_page_by_title and pass the title that way and it'll return the post object with that title.
I upgraded my old site from wordpress version 3.4 to 4.4 recently. Suddenly I am getting a PHP warning as per below:
Warning: Missing argument 2 for wpdb::prepare(), called in ...../wp-content/themes/...functions/admin-functions.php on line 1543 and defined in .......public/wp-includes/wp-db.php on line 1246
Below are the codes for admin-functions.php:
global $wpdb;
$query = "SELECT *,count(*) AS used FROM $wpdb->postmeta WHERE meta_key = '_wp_page_template' AND meta_value = '$filename' GROUP BY meta_value";
$results = $wpdb->get_row($wpdb->prepare($query),'ARRAY_A'); // Select thrid coloumn accross
if(empty($results))
return false;
and wp-db.php
public function prepare( $query, $args ) {
if ( is_null( $query ) )
return;
You need to use placeholders and add the variable as an argument to prepare,%s is a placeholder for string value,assuming it is string from your quotes
$query = "SELECT *,count(*) AS used FROM $wpdb->postmeta
WHERE meta_key = '_wp_page_template' AND meta_value = %s
GROUP BY meta_value";
$results = $wpdb->get_row($wpdb->prepare($query,$filename),'ARRAY_A'); // Select thrid coloumn accross
I would recommend reading the documentation for $wpdb->prepare.
Prepare requires at least two arguments to be passed in. The first is the query, using placeholders (%s for a string and %d for a number), and the second is the list of variables / values to place into the query instead of the placeholders.
For your specific case, I'm demonstrating in a bit longer format so you can see clearly:
global $wpdb;
// Old query. Let's get it ready for prepare...
// $query = "SELECT *,count(*) AS used FROM $wpdb->postmeta WHERE meta_key = '_wp_page_template' AND meta_value = '$filename' GROUP BY meta_value";
// New query, ready for prepare:
$query = "SELECT *,count(*) AS used FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = %s GROUP BY meta_value";
// Now we pass that into prepare, along with the two values we want replaced
$wpdb->prepare($query, '_wp_page_template', $filename);
// And we execute the query...
$results = $wpdb->get_row($query,'ARRAY_A');
Note that you can use the placeholders for as many values as you want, but the idea is that you use them for any value that is user input. If the value may be posted through a form, for example, you absolutely want to use prepare on that value. Example:
$post_id = $_POST['post_id'];
$query = 'SELECT * FROM $wpdb->postmeta WHERE post_id = %d';
$query = $wpdb->prepare($query, $post_id);
Hopefully this helps!
You need to pass $meta_key as second argument.
eg:-
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'miles';
$allmiles = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$meta_key
) );
echo "<p>Total miles is {$allmiles}</p>";
?>
so here your second second argument is $filename.
Reference :- Class Reference / wpdb
Is there any way to see if a post exists by a meta value?
For instance, lets say I want to see if another post has a unique meta value of "pictureID", and if so do something else.
Is there a way I could write that clause in php?
Thank you
if you dont know the post id then
you can use custom wordpress query to check post meta according to key like
global $wpdb;
$wpdb->get_results( "select * from $wpdb->postmeta where meta_key = 'pictureID' " );
And then you can get all results with post id and then get that post data.
Hope this helps ;)
You can use a standard WP_Query to return posts by meta_key using the meta_query argument and EXISTS compare type.
// query for all posts with the pictureID meta key set
$args = array(
'post_type' => 'post', // or your_custom_post_type
'meta_query' => array(
array(
'key' => 'pictureID',
'compare' => 'EXISTS',
),
),
}
// create a custom query
$my_query = new WP_Query( $args );
// loop over your query, creating a custom The Loop
if ( $my_query->have_posts() ): while ( $my_query->have_posts() ): $my_query->the_post();
// $post is now posts that have a pictureId meta value
endwhile; endif;
// reset $post
wp_reset_postdata();
If you want to quickly grab a random post_id that has this meta_key set you can go to the database directly (bypassing caching, etc).
global $wpdb;
// SQL statement to fetch the post_id using a meta_key and a published post
$sql = <<<SQL
SELECT post_id
FROM {$wpdb->postmeta} pm
JOIN {$wpdb->posts} p
ON p.ID = pm.post_id
AND post_status = 'publish'
AND post_type = 'post'
WHERE meta_key = 'pictureID'
AND meta_value != ''
AND post_id != %d
ORDER BY RAND()
LIMIT 1
SQL;
// exclude the current post by replacing %d with the current ID
$sql = $wpdb->prepare( $sql, $post->ID );
// use get_var() to return the post_id
$post_id = $wpdb->get_var( $sql );
first try to get meta value for post get_post_meta()
$postMetaValue=get_post_meta($postId,"meta_key",true);
if($postMetaValue=='pictureID')
{
//do as you want
}
I have a Mysql query set outside the wordpress loop, like the one below, which doesn't work. I would like to know how can I filter the sql results based on the author that created the post.
global $post;
$post_author = $post->post_author;
$sQuery = "SELECT DATE_FORMAT((post_date), '%M/%Y') 'Month',
FROM wp_posts p WHERE p.post_author = '$post_author'
Any assistance is appreciate it.
Thank you,
You have an extra comma after 'Month'. Try this:
$post_author = $post->post_author;
$sQuery = "SELECT DATE_FORMAT((post_date), '%M/%Y') 'Month' FROM wp_9691posts p WHERE p.post_author = '$post_author'";
I also added the final " to enclose the query string.
I created a custom taxonomy named 'technologies' but cannot query multiple terms like I can with categories or tags.
These querys DO work:
query_posts('tag=goldfish,airplanes');
query_posts('technologies=php');
However, neither of the following work correctly:
query_posts('technologies=php,sql');
query_posts('technologies=php&technologies=sql');
My objective: Show all posts with a technology of 'php' and all posts with a technology of 'sql'
Any ideas? Is this even possible? Thanks!
Apparently query_posts cannot help in this specific situation. (Hopefully it will be added in future versions of Wordpress!) The solution is to use a custom select query like the following:
SELECT *
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
WHERE $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'technologies'
AND $wpdb->terms.slug = 'php' OR $wpdb->terms.slug = 'css'
ORDER BY $wpdb->posts.post_date DESC
More information can be found at the Wordpress Codex:
http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
This is a bit of a delayed reply, but it's first on Google at the moment for "wordpress related posts by multiple terms" so thought I'd contribute my findings.
Since this question was posted Wordpress has been changed to allow for this type of query. This will give you a list of posts related by any of the custom taxonomy terms assigned to an object:
$post_cats = wp_get_object_terms(get_the_ID(), 'video_category', array('fields' => 'ids'));
$args=array(
"tax_query" => array(
array(
"taxonomy" => "video_category",
"field" => "id",
"terms" => $post_cats
)
),
'post__not_in' => array(get_the_ID()),
'post_type' => 'video',
'posts_per_page' => 8,
'caller_get_posts' => 1
);
$related_by_cats = new WP_Query($args);
This is my first contribution to SO, I hope it's up to standards.
You can use this plugin:
http://scribu.net/wordpress/query-multiple-taxonomies/
Does this work? query_posts('tag=bread+baking+recipe')
From: http://codex.wordpress.org/Template_Tags/query_posts
OK, so here is my crack at this. It's a little hacky, but it works. The big downside is that any other query variables need to be re-added, as when multiple terms are invoked, the fail strips out all of the query vars.
Also, I did not test this against querying across multiple taxonomies. This only works within a specific taxonomy. Use at your own risk.
function multi_tax_terms($where) {
global $wp_query;
if ( strpos($wp_query->query_vars['term'], ',') !== false && strpos($where, "AND 0") !== false ) {
// it's failing because taxonomies can't handle multiple terms
//first, get the terms
$term_arr = explode(",", $wp_query->query_vars['term']);
foreach($term_arr as $term_item) {
$terms[] = get_terms($wp_query->query_vars['taxonomy'], array('slug' => $term_item));
}
//next, get the id of posts with that term in that tax
foreach ( $terms as $term ) {
$term_ids[] = $term[0]->term_id;
}
$post_ids = get_objects_in_term($term_ids, $wp_query->query_vars['taxonomy']);
if ( !is_wp_error($post_ids) && count($post_ids) ) {
// build the new query
$new_where = " AND wp_posts.ID IN (" . implode(', ', $post_ids) . ") ";
// re-add any other query vars via concatenation on the $new_where string below here
// now, sub out the bad where with the good
$where = str_replace("AND 0", $new_where, $where);
} else {
// give up
}
}
return $where;
}
add_filter("posts_where", "multi_tax_terms");
It's somehow silly that after implementing custom taxonomies in WP there are no built-in functions to use them at will, and the documentation is close to non-existent. I was looking for a solution, this query solves it (and made my day). Thanks.
Still, sadly I'm too dumb (OOP blind) to make it into a function so I don't repeat it all over.
I get: **Fatal error**: Call to a member function get_results() on a non-object
I guess I don't know how to call $wpdb from within a function.
it should be like this:
global $wp_query;
query_posts(
array_merge(
array('taxonomy' => 'technologies', 'term' => array('sql', 'php')),
$wp_query->query
)
);
that works for custom post_types, at least.
Hey, I also faced the same problem once. If you don't have many multiple values, then you can do it in the following way, rather than writing a raw SQL query:
$loop = new WP_Query(array('technologies' => 'php','technologies' => 'sql'));
Then you can loop through the wp_query object created here.
Though this is a very old post and am sure you have already solved the problem. :)
//equivalent to get_posts
function brand_get_posts($args=array()){
global $wpdb;
$sql = "SELECT p.* ";
$sql.= " FROM $wpdb->posts p";
$sql.= " LEFT JOIN $wpdb->term_relationships term_r ON(p.ID = term_r.object_id)";
$sql.= " LEFT JOIN $wpdb->term_taxonomy term_t ON(term_r.term_taxonomy_id = term_t.term_taxonomy_id)";
$sql.= " LEFT JOIN $wpdb->terms terms ON(term_t.term_id = terms.term_id)";
$sql.= " WHERE 1=1 ";
if(!empty($args['post_type'])){
$sql.= " AND p.post_type = '".$args['post_type']."'";
}
$sql.= " AND p.post_status = 'publish'";
if(!empty($args['taxonomy'])){
$sql.= " AND term_t.taxonomy = '".$args['taxonomy']."'";
}
if(!empty($args['terms'])&&is_array($args['terms'])){
$sql.= " AND terms.slug IN ('".implode(",",$args['terms'])."')";
}
$sql.= " ORDER BY p.post_date DESC";
if(!empty($args['posts_per_page'])){
$sql.=" LIMIT ".$args['posts_per_page'];
}
if(!empty($args['offset'])){
$sql.=" OFFSET ".$args['offset'];
}
//echo '<h1>'.$sql.'</h1>';
return $wpdb->get_results($sql);
}