Querying WordPress with SELECT SQL_CALC_FOUND_ROWS - php

So, I've recently taken on a job making changes to the WordPress theme for arena . govspace . gov . au and I've been asked to look into why posts posted on the same day do not appear in order according to the time they were posted.
Now, the way the content is pulled in is not the way I am used to doing it in WordPress. I would normally use a WP_Query, so the examples below are a little out of my wheelhouse.
This function is responsible querying for the output for this page: https://arena.govspace.gov.au/news-media/media-releases/
function SQLQueryPost( $post_type,$meta_key,&$paged,&$rows,&$total_row, $limit_query = "limit 10"){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
global $wpdb;
$test = $wpdb->posts;
$sql = 'SELECT SQL_CALC_FOUND_ROWS meta_value, id, post_title
FROM '.$wpdb->posts.' join '.$wpdb->postmeta.' on '.$wpdb->posts.'.id = '.$wpdb->postmeta.'.post_id
WHERE
meta_value != "" and meta_key = "'.$meta_key.'"
and post_status = "publish"
and post_type = "'.$post_type.'"
order by STR_TO_DATE( meta_value, "%d-%m-%Y") DESC
'.$limit_query.' offset '.($paged - 1 )*10;
$rows = $wpdb->get_results($sql);
$total_row = $wpdb->get_var( "SELECT found_rows();" );
}
For this query, I simply changed the line order by STR_TO_DATE( meta_value, "%d-%m-%Y") DESC to order by post_date DESC and magically it now orders them by date and time.
This function is responsible for pulling more than one content type for this page: https://arena.govspace.gov.au/news-media/
function SQLQueryPostMulti( $post_types,$meta_key,&$paged,&$rows,&$total_row, $limit_query = "limit 10"){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
global $wpdb;
$test = $wpdb->posts;
$sql = 'SELECT SQL_CALC_FOUND_ROWS meta_value, id, post_title, post_type
FROM '.$wpdb->posts.' join '.$wpdb->postmeta.' on '.$wpdb->posts.'.id = '.$wpdb->postmeta.'.post_id
WHERE
meta_value != ""
and post_status = "publish"
and post_type IN (' . $post_types . ')
order by STR_TO_DATE( meta_value, "%d-%m-%Y") DESC
'.$limit_query.' offset '.($paged - 1 )*10;
$rows = $wpdb->get_results($sql);
$total_row = $wpdb->get_var( "SELECT found_rows();" );
}
This query seems to be a little trickier. I attempted the same change (order by STR_TO_DATE( meta_value, "%d-%m-%Y") DESC to order by post_date DESC) but in this case the page returns the exact same entry for all 10 results.
Basically, if anyone could provide any kind of insight as to how I can make this query not only order the posts by day, but to also order them by time posted on that day, I would be extremely grateful.

Related

Wordpress wp query for custom post type category

I am working on pagination in WordPress, pagination working fine for all posts, But I need posts based on category
Now I am using this query for getting all post
$per_page = 8;
$start = $page * $per_page;
$page = sanitize_text_field($_POST['page']);
$wpdb->get_results($wpdb->prepare("
SELECT * FROM " . $table_name . " WHERE post_type = 'articles' AND post_status = 'publish' ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page ));
Can anyone tell me how to display post based on category, I am using custom post type('articles').
Thanks
I have tried with this that is working with me.You may help this code.
Here, you have to join some tables to get post based on category. For that I used join in query.You are using ajax and you will get category_name in POST and that will be assign to related table.
Updated:
$per_page = 8;
$start = $page * $per_page;
$page = sanitize_text_field($_POST['page']);
$category_name = $_POST['category_name'];
$wpdb->get_results($wpdb->prepare("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->terms.name = ''
AND $wpdb->term_taxonomy.taxonomy LIKE '%".$category_name."%'
AND $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'articles'
ORDER BY post_date DESC LIMIT %d, %d", $start, $per_page));

PHP Search with SQL (LIKE) doesn't work

I want to create a search page for my website, but my SQL query doesn't return what I want.
This is my SQL query
SELECT * FROM blog_posts WHERE post_content LIKE '%" . Addslashes($_GET['s']) . "%' AND post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC lIMIT 0, 4;
But it only return the published posts, it doesn't return the searched post
This is my search page : https://lite.the-scientist.fr/search

Wordpress Get Images using MySQL

I have an old function which uses the post excerpt to hold the image thumbnail. It was a bit hackey and worked for a long time.
Now I need to use the post excerpt for, you know, an excerpt. So I'm looking to update this function to grab the image src info straight from the post attachments instead.
The question:
How can I update the $before_sql SQL code below to grab the first attached image in the post attachment?
The code:
(I think I am only concerned about the sql portion as the rest should clean itself up?) There's more code section too, but instead of pasting ALL of it here, this snippet should be enough.
$before_sql = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' and post_date < '$cur_post_date' ORDER BY post_date DESC LIMIT $thumbnum";
$before_results = $wpdb->get_results($before_sql);
if($before_results) {
foreach ($before_results as $before_result) {
$post_title = stripslashes($before_result->post_title);
$permalink = get_permalink($before_result->ID);
$post_excerpt = ($before_result->post_excerpt);
$output="<div class=\"thumbnails\">" . $post_excerpt . "<br />‹</div>\n " . $output;
}
}
To get the first attachment with the posts in one query you can do in this way
SELECT *,
(SELECT guid FROM `wp_posts` WHERE post_type ='attachment' AND post_parent=wp.`ID` ORDER BY post_date ASC LIMIT 1 ) AS attachment
FROM `wp_posts` wp
ORDER BY post_date ASC will get the first image if you want the latest uploaded image you can simply use DESC ORDER BY post_date DESC
Here is your query
$before_sql = "SELECT ID, post_title, post_excerpt,
(SELECT guid FROM $wpdb->posts WHERE post_type ='attachment' AND post_parent=wp.`ID`
ORDER BY post_date ASC LIMIT 1 ) AS attachment
FROM $wpdb->posts wp WHERE wp.post_status = 'publish' AND wp.post_type = 'post'
and wp.post_date < '$cur_post_date' ORDER BY wp.post_date DESC LIMIT $thumbnum";
It works fine for me
This is the query which will fetch those posts only which has the attachments on it
$before_sql = "SELECT ID, post_title, post_excerpt,
(SELECT guid FROM $wpdb->posts WHERE post_type ='attachment' AND post_parent=wp.`ID`
ORDER BY post_date ASC LIMIT 1 ) AS attachment
FROM $wpdb->posts wp WHERE wp.post_status = 'publish' AND wp.post_type = 'post'
and wp.post_date < '$cur_post_date' HAVING attachment IS NOT NULL ORDER BY wp.post_date DESC LIMIT $thumbnum";

How to link to the right page of a topic in a search result?

I have a search function in a forum where the search results will be displayed 10 at the time. The user can then look at the next or previous 10 search results. The results show different topics where the searched words are to be found. Everything works like I want it to.
The issue is when I want the user to be able to click a result and end up on the right page of that topic. For instance post nr 14 in a certain topic must be viewed on page 2 ( using LIMIT 10,10 in the SQL query on the topic page). I send the LIMIT parameter as a $_GET in the link.
How can I retrieve the row number of each topic in the results out of the total numbers of that specific topic when ordering by the date it was posted? Everything is always displayed in that order. I would like to use $nr = $nr-1; //and then
$limit = floor($nr / 10) * 10;
on that number to be able to send the right LIMIT parameter with the link in the search result.
Here's the PDO used to get the search results:
$query = 'SELECT t.topic_id, t.topic_cat, t.topic_subject, p.post_content, p.post_id, UNIX_TIMESTAMP(p.post_date) AS post_date
FROM posts p
LEFT JOIN topics t ON p.post_topic = t.topic_id
WHERE p.post_content LIKE :search OR t.topic_subject LIKE :search ORDER BY UNIX_TIMESTAMP(p.post_date) DESC LIMIT :start, :size';
$statement = $db->prepare($query);
$statement->bindValue(':search', '%'.$search.'%');
$statement->bindValue(':start', $start2, PDO::PARAM_INT);
$statement->bindValue(':size', $pagesize, PDO::PARAM_INT);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$array[$row['topic_subject']][] = $row['post_id'];
$nr = count($array[$row['topic_subject']]) - 1;
echo '<div class="search_result"><div class="search_topic"><a href="topic_view.php?id=' . $row['topic_id'] . '&cat_id=' . $row['topic_cat'] . '
&start=' . floor($nr / 10) * 10 . '#anchor_' . $row['post_id'] . '">' . $row['topic_subject'] . '</a><span style="float:right;color:#696969">'
. date("M d, Y",$row['post_date']) . '</span></div><div class="search_post">' . $row['post_content'] . '</div></div>';
}
} $statement->closeCursor();
It is the start parameter in the link that I somehow need to grab in the query so I don't have to do a new DB call for each post_id in the while loop.
Assuming, that you only know, the ID of the post, I would go like this:
SELECT
count(*)
FROM
`posts`
WHERE
date <= ( SELECT date FROM `posts` WHERE post_id = '$id' )
ORDER BY
date DESC;
This will give you the number of row this post is. After that, just do some php code like:
$start = floor( $nr / 10 ) * 10;
$end = ceil( $nr / 10 ) * 10;
For multiple IDs:
SELECT topic_id, (
SELECT
count(*)
FROM
`posts`
WHERE
date <= ( SELECT date FROM `posts` u1 WHERE u1.topic_id = u2.topic_id )
) AS row
FROM
`posts` u2
WHERE
topic_id IN ( '$id1', '$id2', '$id3' )
ORDER BY
date DESC;
$query = 'SELECT :start as start, t.topic_id, t.topic_cat, t.topic_subject,
p.post_content, p.post_id, UNIX_TIMESTAMP(p.post_date) AS post_date
FROM posts p
LEFT JOIN topics t ON p.post_topic = t.topic_id
WHERE p.post_content LIKE :search OR t.topic_subject LIKE :search
ORDER BY UNIX_TIMESTAMP(p.post_date) DESC LIMIT :start, :size';
then access through $start = $row['start']
$nr = count($array[$row['topic_subject']])+$start - 1;
I had a problem as you said. I think this links is useful for you.
I have done these successfully, I hope be useful you:
1. http://www.awcore.com/dev/1/3/Create-Awesome-PHPMYSQL-Pagination_en
2. http://www.9lessons.info/2009/09/pagination-with-jquery-mysql-and-php.html

SQL exclude first ID entry

I need to exclude first id entry, and display the rest on my wordpress, I have never used sql before.
$all_users_id = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s ASC", $sort ));
One way would be to use something like
SELECT *
FROM Table
WHERE ID > (SELECT MIN(ID) FROM Table)
I am not familiar with Wordpress, but try this:
$all_users_id = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users WHERE $wpdb->users.ID NOT IN (SELECT MIN($wpdb->users.ID) FROM $wpdb->users) ORDER BY %s ASC", $sort ));
$all_users_id = $wpdb->get_col( $wpdb->prepare("SELECT `$wpdb->users.ID` FROM `$wpdb->users` WHERE `$wpdb->users.ID` != 1 ORDER BY %s ASC", $sort ));
The query used:
SELECT `$wpdb->users.ID`
FROM `$wpdb->users`
WHERE `$wpdb->users.ID` != 1
ORDER BY %s ASC
Fast and simple... Without sub-querys! :)
If it's a mysql db then use the limit clause:
SELECT `$wpdb->users.ID`
FROM `$wpdb->users`
ORDER by $sort ASC
LIMIT 1,9999999
C.

Categories