In "category.php" file I need to order my posts in this strange way:
First all the posts where author is different than "admin" (in alphabetical order by title)
Than all the post by "admin" (in the same alphabetical order)
Here is the standard code I use to do my query:
<?php global
$wp_query;
query_posts(
array_merge(
array('orderby' => 'title', 'order' => 'ASC'),
$wp_query->query
)
);
?>
Any idea about how to accomplish it without nesting two queries?
Thanks in advance!
EDIT: Following is some code that was tried, as suggested by Sepster in a previous version of his answer. But at the moment this code starts showing all the posts from 'admin' (instead of the others) until the posts with author different than 'admin' come. At that point it breaks the results and jump to the next page of results.
<?php
global $wp_query;
query_posts(
array_merge(
array('orderby' => 'title', 'order' => 'ASC'),
$wp_query->query
)
);
$adminPosts = false;
for ($i=1; $i<=2; $i++) {
while ( $wp_query->have_posts() ) {
$wp_query->the_post();
$author = get_the_author();
if ($author == 'admin' && $adminPosts == false) break;
if ($author != 'admin' && $adminPosts == true) break;
// ALL MY STUFF
} // end while
rewind_posts();
$adminPosts=true;
} // end FOR
?>
Update:
I've finally come up with a somewhat workable solution for this, but it's fair to say this really is an excercise in academics; Yes, it's do-able without executing a second loop, but really, it's pretty convoluted.
The solution is, in summary
Develop a custom SQL statement that will return the rows in the order required.
This is because in SQL, the only way to get the results in the order you need is by doing a UNION of your two subsets. To my knowledge there's no way of doing that using the "normal" WP query operations.
Execute this query, and loop over its results rather than a standard "the loop".
This is because we're getting back a recordset, rather than a WP_Query object.
Set the "Blog pages show at most X posts" setting to 1.
(on /wp-admin/options-reading.php)
A common complaint is pagination breaking when using custom queries (incidentally, the query_posts() method you're using is susceptible to this issue).
There are numerous turorials on how to do this properly, eg:
https://codex.wordpress.org/Making_Custom_Queries_using_Offset_and_Pagination
https://codex.wordpress.org/Pagination#Troubleshooting_Broken_Pagination
The first of those recommends the implementation of "Offset and Manual Pagination".
The closest I've found to an implementation of this in conjunction with a custom SQL statement is this https://wordpress.stackexchange.com/a/28717. I've borrowed heavily from this answer (and so I recommend you go over and give it an up-vote!).
However, this technique (among other more "standard" custom query approaches) suffers from a known behaviour where WP produces a 404 on the final page (if I understand correctly, because WP is still using its own query and associated max-page=posts-per-page/posts calculations to map between the page number in the URL and the delivered content).
Refer http://wordpress.org/support/topic/explanation-and-workaround-for-error-404-on-category-pagination?replies=14 for details about this issue, and a proposed solution (which unfortunately won't work for our custom SQL approach).
A known "work-around" for this issue is to reduce the number of posts-per-page to 1, as per eg http://wordpress.org/support/topic/custom-post-type-pagination-404-on-last-page
So, assuming you're happy with a global setting of 1 posts-per-page (remember you'd need to override this manually in your custom queries), here's the code:
functions.php:
...
function get_users_posts_last($userDisplayName = 'Admin', $categoryName = '') {
global $wpdb, $paged, $max_num_pages;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_per_page = 5;
$offset = ($paged - 1)*$post_per_page;
$sql = "
SELECT SQL_CALC_FOUND_ROWS q.* FROM
(
(
SELECT
p.*
FROM
{$wpdb->posts} p
INNER JOIN {$wpdb->users} u ON p.post_author = u.ID
LEFT JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
WHERE
tt.taxonomy = 'category'
AND p.post_status = 'publish'
AND p.post_type = 'post'
AND u.display_name != '{$userDisplayName}'
" . ( $categoryName != '' ? "AND t.name = '{$categoryName}'" : "" ) . "
ORDER BY
p.post_title ASC
)
UNION
(
SELECT
p.*
FROM
{$wpdb->posts} p
INNER JOIN {$wpdb->users} u ON p.post_author = u.ID
LEFT JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
LEFT JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
WHERE
tt.taxonomy = 'category'
AND p.post_status = 'publish'
AND p.post_type = 'post'
AND u.display_name = '{$userDisplayName}'
" . ( $categoryName != '' ? "AND t.name = '{$categoryName}'" : "" ) . "
ORDER BY
p.post_title ASC
)
) q
LIMIT {$offset}, {$post_per_page};
";
$sql_result = $wpdb->get_results( $sql, OBJECT);
$sql_posts_total = $wpdb->get_var( "SELECT FOUND_ROWS();" );
$max_num_pages = ceil($sql_posts_total / $post_per_page);
return $sql_result;
}
...
category.php:
...
$postList = get_users_posts_last('admin'); // Note you can also pass a category name if necessary
if($postList) {
global $post;
foreach( $postList as $key=>$post ) {
setup_postdata($post);
// Render the post here
?>
<header class='entry-header'><h1 class='entry-title'><?php the_title(); ?></h1></header>
<div class='entry-content'><?php the_content(); ?></div>
<?php
}
// Render pagination here
?>
<div class="navigation">
<div class="previous panel"><?php previous_posts_link('« Previous page',$max_num_pages) ?></div>
<div class="next panel"><?php next_posts_link('Next page »',$max_num_pages) ?></div>
</div>
<?php
}
...
Or, just set up two separate queries ;-)
Related
I have a big problem with one of my sites. I have one category that stores other categories. The problem is that WordPress uses WP_Query->get_posts and gets all the posts on this main category page. Even tho I deleted everything inside and I left only the_header and the_footer it still does the query. Structure is like this Category>Subcategory>posts. The problem is that WordPress is doing the query for all posts that are in my subcategories.
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
LEFT JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (13,14,15,24,25,26,27,28,29,102,130,154,256) )
The query is much larger than this, it takes around 22 seconds to load.
My code works fine, if I move the code in a custom page it loads in 0.80, but in the custom_category page loads in 22-28 seconds. I would like to prevent SELECT SQL_CALC_FOUND_ROWS wp_posts.ID from running in this category. I can't change anything about the URLs since the site is in production and has really good positions. Need to do something ASAP and I'm out of ideas.
I've tried this: https://wpartisan.me/tutorials/wordpress-database-queries-speed-sql_calc_found_rows but it doesn't matter, still the same loading speed.
This is my code:
<?php
GLOBAL $wpdb;
$subcategorii = $wpdb->get_results("select term_id, name, slug from $wpdb->terms where is_mother_cat = '1' ORDER BY term_id DESC");
// total numar de postari de afisat
$per_page = 28;
// extragem numarul total de postari
$total_rows = count($subcategorii);
// setam numarul total de pagini
$pages = ceil($total_rows / $per_page);
// extragem page curenta
$current_page = (#$_GET['page'] ? #$_GET['page'] : 1);
$current_page = ($total_rows > 0) ? min($pages, $current_page) : 1;
// offset
$start = $current_page * $per_page - $per_page;
// salvam in array doar postarile din page curenta
$subcategorii_array = array_slice($subcategorii, $start, $per_page);
foreach ($subcategorii_array as $subcats) {
echo '<li class="border-radius-5 box-shadow">';
//z_taxonomy_image($subcats->term_id, 'thumbnail', array('alt' => $subcats->name));
echo '<span>'.$subcats->name.'</span>';
echo '</li>';
}
?>
Fixed this problem with this function that I found. But another one appeard.
Now the WP_Term_Query->get_terms() is called on that page calling all the posts. At least is 10 seconds faster. Anyone any ideea what is happening here?
SELECT t.*, tt.*
FROM wp_terms AS t
INNER JOIN wp_term_taxonomy AS tt
ON t.term_id = tt.term_id
WHERE tt.taxonomy IN ('category')
Function that fixes the problem:
/* apply this filter only on relevant to you pages */
function mb_bail_main_wp_query( $sql, WP_Query $wpQuery ) {
if ( $wpQuery->is_main_query() && is_category(8133) ) {
/* prevent SELECT FOUND_ROWS() query*/
$wpQuery->query_vars['no_found_rows'] = true;
/* prevent post term and meta cache update queries */
$wpQuery->query_vars['cache_results'] = false;
return false;
}
return $sql;
}
add_action( 'posts_request', 'mb_bail_main_wp_query', 10, 2 );
I've been searching through the past two days to find out where exactly could the Woocommerce products thumbnails (images) texts and URL's are stored inside the database tables, but still cannot figure this out!
I'm in a situation where I must use SQL queries to move the products data into another tables, and I have to implement the process from my phpmyadmin panel.
I already searched the wp_posts and wp_postmeta tables, wp_posts contains a guide column for the url to the product which post_type like 'product%', So far I know that in general the post stores it's thumbnalis link inside one of the posts with a type of attachment , while I need the posts with a post_type of product or like so.
Hope I can find some answers here, Thanks.
You can use the Wordpress WP_Query to get the thumbnail image of product.
$args = array(
'post_type' => 'product', //post type of product
'posts_per_page' => -1
);
$query= new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
global $product;
//woocommerce_get_product_thumbnail is use to get the product thumbnail link
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
endwhile;
wp_reset_query();
Solution 2- using the custom query as you mention in query.
//Using custom query get the details from wp_postmeta and wp_posts
//_wp_attached_file - meta key for image
$querystr = "SELECT p.*, pm2.meta_value as product_image FROM wp_posts p LEFT JOIN
wp_postmeta pm ON (
pm.post_id = p.id
AND pm.meta_value IS NOT NULL
AND pm.meta_key = '_thumbnail_id'
)
LEFT JOIN wp_postmeta pm2 ON (pm.meta_value = pm2.post_id AND pm2.meta_key = '_wp_attached_file'
AND pm2.meta_value IS NOT NULL) WHERE p.post_status='publish' AND p.post_type='product'
ORDER BY p.post_date DESC";
$upload_dir = wp_upload_dir();
//get wp_upload url
$wp_upload_url = $upload_dir['baseurl'];
$pageposts = $wpdb->get_results($querystr, OBJECT);
foreach ($pageposts as $post){
echo "<br /><a href='".$post->guid."'><img src='". $wp_upload_url.'/'.$post->product_image."'>".$post->post_title."</a>";
}
I have a movie-database, i want to know which movies actor A and B has both been featured in.
function getmoviefromactor(){
global $wp_query;
global $wpdb;
global $post;
$loop = new WP_Query(array(
'post_type' => 'movies',
'actors' => 'A', 'B',
'posts_per_page' =>-1,
));
print_r($loop);
while ( $loop->have_posts() ) : $loop->the_post();
?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php
the_content();
endwhile;
}
The problem with this code is that Wordpress by default is searching for Actor A or B and displaying every movie they've been featured in and not just the movie(s) they've both been featured in.
Thanks,
Marten
EDIT:
I think im almost there, im stuck in a SQL-query, it works perfect if i just search for one of the actors, the problem accors when i search for both, which results in an empty array.
When i do the manual search in the SQL query i see duplicate content with different term.slugs, is there any workaround for this?
global $wpdb;
$querystr = "
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 = 'movies'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->term_taxonomy.taxonomy = 'actors'
AND $wpdb->terms.slug = 'A'
AND $wpdb->terms.slug = 'B'
ORDER BY $wpdb->posts.post_date DESC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
print_r($pageposts);
All the best,
Marten
try this:
'actors' => array('A', 'B')
After doing some digging and experimenting, found a way to do it right. It involves posts_join and posts_where filters:
$actor1 = 'A';
$actor2 = 'B';
function join_it($join) {
$join = " INNER JOIN $wpdb->term_relationships tr1 ON($wpdb->posts.ID = tr1.object_id)
INNER JOIN $wpdb->term_taxonomy tt1 ON(tr1.term_taxonomy_id = tt1.term_taxonomy_id)
INNER JOIN $wpdb->terms t1 ON(tt1.term_id = t1.term_id)
INNER JOIN $wpdb->term_relationships tr2 ON($wpdb->posts.ID = tr2.object_id)
INNER JOIN $wpdb->term_taxonomy tt2 ON(tr2.term_taxonomy_id = tt2.term_taxonomy_id)
INNER JOIN $wpdb->terms t2 ON(tt2.term_id = t2.term_id)";
return $join;
}
function where_it($where) {
global $actor1;
global $actor2;
$where = " WHERE $wpdb->posts.post_type = 'movies'
AND tt1.taxonomy = 'actors'
AND tt2.taxonomy = 'actors'
AND t1.slug = {$actor1}
AND t2.slug = {$actor2}";
}
function getmoviefromactor(){
global $wp_query;
global $wpdb;
global $post;
add_filter('posts_join','join_it',10);
add_filter('posts_where','where_it',10);
$loop = new WP_Query();
remove_filter('posts_join','join_it',10);
remove_filter('posts_where','where_it',10);
print_r($loop);
while ( $loop->have_posts() ) : $loop->the_post();
?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php
the_content();
endwhile;
}
The posts_where and posts_join filters adds where and join clauses respectively to the loop. I tested a similar code with my own site but if it doesn't work, please let me know.
I have been presented with this code. The code displays the title headings of the latest 10 WordPress posts from the database. What I need to do is to eliminate a particular category from this. Can anyone help?
<?php require_once 'news/wp-config.php';
$howMany = 0;
$query ="SELECT `ID`, `post_title`,'post_category', `guid`,SUBSTRING_INDEX(`post_content`, ' ', 100) AS `post_excerpt` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_type` = \"post\" ";
$posts = $wpdb->get_results($query);
$posts = array_reverse($posts);
foreach($posts as $post)
{
if($howmany<10)
{
$link = $post->guid;
echo "<li><a target='_blank' href='$link'>$post->post_title</a></li>";
$howmany++;
}
}
?>
Or, you could use a second loop, something like this :
<div>
<h3>Fresh Posts</h3>
<ul>
<?php
$my_query = new WP_Query("cat=-3&order=DESC&posts_per_page=10");
echo "<pre>"; print_r($my_query->query_vars); echo "</pre>"; // shows the variables used to parse the query
echo "<code style='width: 175px;'>"; print_r($my_query->request); echo "</code>"; // shows the parsed query
while ($my_query->have_posts()) : $my_query->the_post(); //standard loop stuff
$do_not_duplicate[] = $post->ID;?>
<li id="post-<?php the_ID(); ?>"><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
</div>
once again WP 2.8.x. Lots of good info here : WordPress loop documentation
Determine the category you don't need and add an extra AND to your WHERE clause:
AND post_category != 3
You can do it either of 2 places. The most efficient is to do it in the query:
$query ="SELECT ID, post_title, post_category, guid, SUBSTRING_INDEX(post_content, ' ', 100) AS `post_excerpt`
FROM $wpdb->posts
WHERE post_status= 'publish'
AND post_type = 'post'
AND post_category!= 'unwanted string' ";
The other place to do it, if for some reason you need all the results, but you want to use the unwanted category somewhere else, is when you retrieve the results:
if($howmany<10 && post['post_category']!='unwanted string') {
'Noticeboard' is the name of the category i want to eliminate. but if i write that, it dispalys a parse error.
Because you must insert the category ID in the query, not the category name.
To get that, just watch in the database wp_categories table.
Some links about wordpress database:
http://blog.kapish.co.in/2008/01/18/wordpress-database-schema/
http://wpbits.wordpress.com/2007/08/08/a-look-inside-the-wordpress-database/
Anyway, I think it's more hard than this. Look at post2cat table.
So, you have to do a subquery.
I am not sure which WP version you are using, so this 'answer' has a few caveats.
Caveat 1 : This is not a complete answer, more like a pointer
Caveat 2 : The query below works with WP 2.8.x so YMMV
The query below shows how to link posts back to their categories. You can use the NOT IN mySQL operator to exclude the category you do not want by its ID
SELECT
wp_posts.*
FROM
wp_posts
INNER JOIN
wp_term_relationships
ON
(wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN
wp_term_taxonomy
ON
(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
WHERE
wp_term_taxonomy.taxonomy = 'category'
AND
wp_term_taxonomy.term_id NOT IN ('3')
AND
wp_posts.post_type = 'post'
AND
(wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future')
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date
DESC
The line breaks and indenting are idiosyncratic, but (hopefully) make it easier for you to see what is going on with this query.
I hope this helps.
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);
}