Delete Old or Redundant Post Metadata from Wordpress - mysql

It appears that somehow in the past, WordPress saved multiple redundant post_meta for post revisions which are no longer in the database.
As a result, I have a ton of post_meta that does nothing and is tied to posts that no longer exist.
Does anyone know how to remove this data from phpMyAdmin with a SQL query?

You can run a mysql query like this; WordPress › Support » SQL Query to delete orphans wp_postmeta, but might be easier and safer to use a plugin like WordPress › Mass Custom Fields Manager « WordPress Plugins or WordPress › Custom Field Taxonomies « WordPress Plugins

"Optimize Database" is the one I use. Setup is very quick and easy. It runs in the background daily cleaning out post-meta orphans, things you have trashed, and useless old "revisions".

This has been explained here in full.
Remove Unnecessary WP Postmeta
All you have to do is add the following in your theme functions.php file
function delete_useless_post_meta() {
global $wpdb;
$table = $wpdb->prefix.'postmeta';
$wpdb->delete ($table, array('meta_key' => '_edit_last'));
$wpdb->delete ($table, array('meta_key' => '_edit_lock'));
$wpdb->delete ($table, array('meta_key' => '_wp_old_slug')); }
add_action('wp_logout','delete_useless_post_meta');

Related

How Do I Bulk Delete All Wordpress Posts in a Specific Category or Before a Specific Date?

I have some categories on a site with over 350,000 active posts some of which have as many as 50,000 posts. The volume makes using a bulk delete plugins not viable because they all timeout and delete nothing. The best feedback I've gotten from the Wordpress support forum is to use WP-CLI but beyond that all they've done is give me a link to the WP-CLI website which contains no example specific to my needs.
I have never used CLI before beyond a failed attempt to run Media Cleaner which resulted in a timeout at 999 seconds. That was months ago so I forget how I tried to do that. Could someone please post a code snippet that could basically be copied and pasted into CLI with the only change I need to make being swapping the category ID or date/ID number of the oldest post I want to keep?
Again, I want to be able to delete all posts from a specific category or before a specific date/ID.
Alternatively, could someone post a SQL statement so that I can do this using MySQL without installing CLI? The SQL would be better because I could apply it to any site without installing let alone learning CLI.
You don't have access to phpmyadmin?
You could avoid all of that just by deleting posts on load:
/**
* REMOVE EVIL POSTS IF AND WHEN LOADED
* add to functions.php
* works on regular posts and simple categories,
* check codex for details if custom post types, custom taxonomies, etc.
**/
add_action( 'template_redirect', 'delete_post_on_load' ) ;
function delete_post_on_load() {
global $post ;
//has term works more consistently if all variables are supplied
if ( has_term( array( 'Category to Go', 'Second Category to Go' ), 'category', $post->ID ) ) {
wp_delete_post( $post->ID, true ) ;
wp_safe_redirect( site_url() ) ; //redirect to home instead of 404 on deletion
exit() ;
}
}

- MySQL - Delete tables (blogs and plugins) from wordpress MU

I manage a new WPMU installation clone but I want clear a part of subdomains.
When I delete a suddomain from Wordpress MU (clone), all tables get dropped but all the tables where a plugin need write is still here.
Then there is SQL command like (to delete all tables in one shot):
DELETE from 'wp_ID' to 'wp_ID'
but delete all primary table and all sub-table like wp_ID_plugin
Because I have some residual table after maybe 10 or 15 tables with ID from plugins.
I ask this because I have a Wordpress MU with over 600 website and I split it into two wordpress MU.
Edit /
I choose another way to try to clean database. I found a sample code
Delete Extra Plugin Tables When a Site Is Deleted in WordPress Multisite
And adapt array for my specific tables
$plugin_tables = array( 'statistics_useronline', 'statistics_visit', 'statistics_visitor', 'csp3_subscribers', 'ewwwio_images', 'mappress_maps', 'mappress_posts', 'revslider_css', 'revslider_layer_animations', 'revslider_navigations', 'revslider_sliders', 'revslider_slides', 'revslider_static_slides', 'sendpress_autoresponders', 'sendpress_list_subscribers', 'sendpress_queue', 'sendpress_subscribers', 'sendpress_subscribers_meta', 'sendpress_subscribers_status', 'sendpress_subscribers_tracker', 'sendpress_subscribers_url', 'sendpress_url', 'statistics_exclusions', 'statistics_historical', 'statistics_pages', 'statistics_search', 'statistics_useronline', 'statistics_visit', 'statistics_visitor', 'yoast_seo_links', 'yoast_seo_meta' );
I will manage this next week, seems work over "test tables"

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hack™ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

PHPStorm warnings on placeholders in WordPress plugin queries

I have a WordPress plugin that I am editing in PHPStorm. PHPStorm finds syntax errors on queries like this when the SQL dialect is set to MySQL:
$foo = $wpdb->get_var(
$wpdb->prepare(
'SELECT `foo` FROM `some_table` WHERE `id` = %d',
$bar
)
);
Specifically, it sees %d and complains with this message:
<expression> expected, got '%'
Of course, %d is a perfectly legitimate placeholder in WordPress queries. Is there a way to configure PHPStorm to accept this? Or do I have to disable all checks on SQL statements, as suggested in this answer?
Note that I am using PHPStorm EAP 8 (138.1751), and the same thing happens with other placeholders like %s.
This is now possible in PHPStorm 8, as explained by this post on the official PHPStorm blog:
Database Language Injection Configuration
To solve it:
Go to Tools > Databases
Make sure a regex matching the placeholders in question is in the list of custom parameters. By default, the list includes \%\w+, which will match %s, %d, etc.
Check the box labeled "Use in other language string literals"
PHPStorm will now correctly recognize placeholders like those used in WordPress.
Nope -- %d is not valid syntax from SQL point of view (ANY currently supported dialect). The WI-3672 and WI-2324 tickets are still valid.
But PhpStorm v8 now supports $var (if you could use it instead of % syntax) -- http://youtrack.jetbrains.com/issue/WI-2450
Since it's WordPress specific question, it's hard for me to give you any real suggestion (especially since I'm not using WordPress myself) excluding that one.
But generally speaking you could use native place holders supported by specific DB engine (check "Examples" section in http://php.net/manual/en/pdo.prepare.php):
unnamed ?
named :id
I just not sure if this can be applied to WordPress development.
P.S.
Generic is the new Keywords only dialect -- fall back to that if using proper SQL dialect shows to many warnings/errors (that are not actual errors).

Need a MySQL query to delete Wordpress comments

My wordpress site was recently hacked so I had to reinstall everything. Wordpress resinstalled, database backups imported, everything fine and dandy. Then I installed the Disqus plugin and synced (Disqus was previously used before the site was hacked). Big no-no apparantly. Now I have a duplicate of every single comment on my site! Even worse, the duplicate comments have been synced BACK to Disqus!
So, I know this is a simple query in PHPMyAdmin but I don't know it! Please help!
Keep in mind that there is a WordPress Stack Exchange website ;)
I would use PHP unless you know the wpdb name off the top of your head. Be sure to back up the DB first! Like so:
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;
}
If he doesn't know how use mysql, I think re editing the wp interface is great, because usually wp creating there build function for queries. And it may lead again to destruction of it.
The only reason why it doesn't work maybe its because of the plug in they use.! I think so.!
The query for deleting in mysql is
Delete from (tablename) where (primarykey)
But I think wordpress has its build in database queries for select delete and update.
Here's another if you use the plugin Disqus
If you're logged into your Disqus account you can also choose to delete a comment at your dashboard. This will remove it from your profile and remove all identifying information from the comment on the original page. Once a comment has been anonymized it cannot be claimed again.