MySQL question: Appending text to a wordpress post, but only if it's in a certain category - mysql

I need to amend (via CONCAT, presumably) something to every wordpress post if it belongs to a certain category (say, category ID 7), but I'm struggling to get it to work.
To test, I'm first trying to select all the relevant posts. So far, I have the following:
SELECT post_title
FROM cruise_wp_posts
LEFT JOIN cruise_wp_term_relationships
ON cruise_wp_term_relationships.object_id = cruise_wp_posts.ID
WHERE term_taxonomy_id = 87;
However, it only lists posts that are only in category 87 - I need all posts that are in category 87 (and possibly other categories too)
I'm a MySQL newbie, and this is really breaking my brain.
Any pointers would be passionately welcomed.

The best way to do it is to filter it in as needed. This way the addition is made everywhere the_content is used and not just in the templates you modify.
<?php
function my_content_concat($the_content) {
if (in_category(7)) {
$the_content .= '<br /><br />foo!';
}
return $the_content;
}
add_filter('the_content', 'my_content_concat', 9);
?>
in_category can take the id, name or slug of your target category.
I put the filter at 9 so that it runs before WordPress texturizes the content. If you don't need that run it at 11.

Why not just use get_the_category( $id ) and ammend the text when you output the post?
$cat = get_the_category( $postID );
if ($cat == 7) {
//Add text here
}

Related

Get all sku for an order through sql

Working on a script to pull some customer order data from various databases and combine them into one output. Most of the stuff works fine, but can't seem to be able to get the sku's for the products of an order.
Noticed there was a meta_key called "_sku" so tried with something like
$sqlMetaSku = "SELECT * FROM wp_postmeta WHERE meta_key='_sku' AND post_id='$post_id'";
$resultMetaSku = $conn->query($sqlMetaSku);
if ($resultMetaSku->num_rows > 0) {
while($rowMetaSku = $resultMetaSku->fetch_assoc()) {echo($sqlMetaSku);
$clientSku = $rowMetaSku["meta_value"];
echo (between ('s:8:', ';s:12', $clientSku));
}
}
but no luck here.
Noticed there was a key called "_order_key" so maybe that's the way to go? I am not sure how to proceed.

MediaWiki: changing the label of a category at the bottom of the page

In mediawiki, is it possible to change the label of a 'Category' at the bottom of an article.
For example for the following article:
=Paris=
blablablablablabla
[[Category:place_id]]
I'd like to see something more verbose like (the example below doesn't work):
=Paris=
blablablablablabla
[[Category:place_id|France]]
Note: I don't want to use a 'redirect' and I want to keep my strange ids because they are linked to an external database.
I do not think mediawiki is supporting this feature.
However, how about using:
[[Category:France]]
in your page, and set it into the category named with your id? France would just be a subcategory of "place_id", and you could use more terms all linked to the parent category. For this, you just need to edit the category page for "France", inserting:
[[Category:place_id]]
An alternative would be to put your page in both categories, but in this case, the id would still be displayed:
[[Category:place_id]]
[[Category:France]]
You could do this with an OutputPageMakeCategoryLinks hook. Alas, the interface for that hook seems to be a bit inconvenient — as far as I can tell, it's pretty much only good for replacing the standard category link generation code entirely. Still, you could do that is you want:
function myOutputPageMakeCategoryLinks( &$out, $categories, &$links ) {
foreach ( $categories as $category => $type ) {
$title = Title::makeTitleSafe( NS_CATEGORY, $category );
$text = $title->getText();
if ( $text == 'Place id' ) {
// set $text to something else
}
$links[$type][] = Linker::link( $title, htmlspecialchars( $text ) );
}
return false; // skip default link generation
}
$wgHooks['OutputPageMakeCategoryLinks'][] = 'myOutputPageMakeCategoryLinks';
(The code above is based on the default category link generation code in OutputPage.php, somewhat simplified; I assume you're not using language variant conversion on your wiki, so I removed the parts that deal with that. Note that this code is untested! Use at your own risk.)

MySql: Best way to run high number of search queries on a table

I have two tables, one is static database that i need to search in, the other is dynamic that i will be using to search the first database. Right now i have two separate queries. First on page load, values from second table are passed to first one as search term, and i am "capturing" the search result using cURL. This is very inefficient and probably really wrong way to do it, so i need help in fixing this issue. Currently page (html, front-end) takes 40 seconds to load.
Possible solutions: Turn it into function, but still makes so many calls out. Load table into memory and then run queries and unload cache once done. Use regexp to help speed up query? Possible join? But i am a noob so i can only imagine...
Search script:
require 'mysqlconnect.php';
$id = NULL;
if(isset($_GET['n'])) { $id = mysql_real_escape_string($_GET['n']); }
if(isset($_POST['n'])) { $id = mysql_real_escape_string($_POST['n']); }
if(!empty($id)){
$getdata = "SELECT id, first_name, last_name, published_name,
department, telephone FROM $table WHERE id = '$id' LIMIT 1";
$result = mysql_query($getdata) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo <<<PRINTALL
{$row[id]}~~::~~{$row[first_name]}~~::~~{$row[last_name]}~~::~~{$row[p_name]}~~::~~{$row[dept]}~~::~~{$row[ph]}
PRINTALL;
}
}
HTML Page Script:
require 'mysqlconnect.php';
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$getdata = "SELECT * FROM $table WHERE $table.mid != '1'ORDER BY $table.$sortbyme $o LIMIT $offset, $rowsPerPage";
$result = mysql_query($getdata) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$idurl = 'http://mydomain.com/dir/file.php?n='.$row['id'].'';
$p_arr = explode('~~::~~',get_data($idurl));
$p_str = implode(' ',$p_arr);
//Use p_srt and p_arr if exists, otherwise just output rest of the
//html code with second table values
}
As you can see, second table may or may not have valid id, hence no results but second table is quiet large, and all in all, i am reading and outputting 15k+ table cells. And as you can probably see from the code, i have tried paging but that solution doesn't fit my needs. I have to have all of the data on client side in single html page. So please advice.
Thanks!
EDIT
First table:
id_row id first_name last_name dept telephone
1 aaa12345 joe smith ANS 800 555 5555
2 bbb67890 sarah brown ITL 800 848 8848
Second_table:
id_row type model har status id date
1 ATX Hybrion 88-85-5d-id-ss y aaa12345 2011/08/12
2 BTX Savin none n aaa12345 2010/04/05
3 Full Hp 44-55-sd-qw-54 y ashley a 2011/07/25
4 ATX Delin none _ smith bon 2011/04/05
So the second table is the one that gets read and displayed, first is read and info displayed if ID is positive match. ID is only unique in the first one, second one has multi format input so it could or could not be ID as well as could be duplicate ID. Hope this gives better understanding of what i need. Thanks again!
A few things:
Curl is completely unnecessary here.
Order by will slow down your queries considerably.
I'd throw in an if is_numeric check on the ID.
Why are you using while and mysql_num_rows when you're limiting to 1 in the query?
Where are $table and these other things being set?
There is code missing.
If you give us the data structure for the two tables in question we can help you with the queries, but the way you have this set up now, I'm surprised its even working at all.
What you're doing is, for each row in $table where mid!=1 you're executing a curl call to a 2nd page which takes the ID and queries again. This is really really bad, and much more convoluted than it needs to be. Lets see your table structures.
Basically you can do:
select first_name, last_name, published_name, department, telephone FROM $table1, $table2 WHERE $table1.id = $table2.id and $table2.mid != 1;
Get rid of the curl, get rid of the exploding/imploding.

Mysql Query to Delete Duplicate Wordpress Comments?

I had an issue with Disqus whereby it created duplicate comments on many posts, sometimes 4 duplicates of the same comment. I've been going through to try and manually remove these but we have more than 10K comments total and unfortunately, this happened haphazardly whereby it only happened to some of the posts. So...
does anyone know of a mysql query whereby I could detect and delete duplicate comments by searching for entries that match in terms of the comment itself or the author? The comment IDs are not duplicate (it created new comment IDs for each) so Im not sure how to do this in mysql (plus Im not very good at it :-)... Any help would be greatly appreciated. Thank you.
Improving on Blackbarn's suggestion, try this (after backing up the db):
global $wpdb;
$comments = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_comments"
." ORDER BY comment_post_ID, comment_content");
$prev = NULL;
foreach($comments as $comment) {
if ($prev && $prev->comment_content == $comment->comment_content
&& $prev->comment_post_ID == $comment->comment_post_ID ) { // add maybe other rules here
$wpdb->query("DELETE FROM ".$wpdb->prefix."_comments WHERE comment_ID = ".$comment->comment_ID);
}
else
$prev = $comment;
}
Write a simple PHP script to clean your comments table (but make a backup before you do it).
Pseudo Code:
// get all the comments
// compare each comment with each comment
// if the content of the comment is the same (or compare all values except of the id, if you want to be sure that nothing gets broken), delete the comment with the higher id
It will be something like this:
global $wpdb;
$comments = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_comments");
foreach($comments as $comment) {
foreach($comments as $compare) {
if(($comment->comment_content == $compare->comment_content) && ($comment->comment_ID != $compare->comment_ID )) { // add maybe other rules here
$wpdb->query("DELETE FROM ".$wpdb->prefix."_comments WHERE comment_ID == $compare->comment_ID");
}
}
Not tested, so use and improve with care...
Database with comments table: http://codex.wordpress.org/images/9/9e/WP3.0-ERD.png

PHP Array Duplicates

my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
What I would like to do is display each user individually, and count the number of contacts each user has. I had a look at the post "How to detect duplicate posts in PHP array, which helped a bit, but I am still stuck.
Please see my code for the query below, I have left out the array duplicate part as it is a pretty mess at the moment.
<?php
$result = mysql_query("SELECT * FROM vines");
while($row = mysql_fetch_array($result)) {
$results=$row['vinename'];
echo $results;
echo "<br />";
}
?>
This result returns the below, obviously these are records from the vinename coloumn.
Marks Vine<br />
Marks Vine<br />
Marks Vine<br />
Tasch Vine<br />
Tasch Vine<br />
Regards
Mark Loxton
Hi there, my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
You can do this in the query itself a lot more easily than in the PHP code afterwards.
SELECT name, COUNT(id) AS count FROM vines GROUP BY name
Just change the SQL Query to
SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename
and then do
echo $row['vinename']." #".$row['counter']."<br />";
I would run two types queries...
1) Select each UNIQUE user from vines.
2) For each user in that set, run a second COUNT query against that user's id in the table "vines".
I hope that helps.
You can create a separate array to store records you've already output there.
<?php
$result = mysql_query("SELECT * FROM vines");
$duplicates = array(); ## store duplcated names here
while($row = mysql_fetch_array($result)) {
$results = $row['vinename'];
if (!array_key_exists($results, $duplicates)) {
echo $results;
echo "<br />";
$duplicates[$results] = 1; ## mark that we've already output this records
}
}
?>
You can try, change your query to use count and group of SQL.
Somoe thing like
$result = mysql_query("SELECT count(*) as total,name FROM vines GROUP by name");
firstly thank you everyone for such awesome input. I seriously did not expect such a quick response. I am seriously grateful.
I used the recommendation from Jitter. I have pretty much been going through so many variations of the above code today, but just needed that missing piece.
Thanks, everyone. Below is what the final code looks like for anyone else who has the same problem in the future.
<?php
$result = mysql_query("SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename ORDER BY counter DESC LIMIT 0, 3");
while($vinerow = mysql_fetch_array($result))
echo $vinerow['vinename']." has ".$vinerow['counter']." tomatos."."<br />";
?>
change your query to:
SELECT distinct * FROM vines