Hook before deleting a file in wordpress - wordpress

Few days ago, I was assigned to task in wordpress. This task is to limit media folder capacity for each user. For example, each user can upload only files only for 100MB. I found a really nice post, which explained and used hooks named wp_handle_upload_prefilter and wp_handle_upload for retrieving the file size and storing them before upload.
Right now, I need to know, or hook some function when user presses "Delete permanently" in media folder, so that I can recalculate the capacity of media folder for specific user. Can anyone help me with this?

In case anyone else needs to react to deleted media, this was my solution to get around the issue that there's no delete media action:
function get_media_item_args( $args ) {
if ($args["delete"] && $_GET["action" == "delete-post"])
{
$current_post_id = !empty( $_GET['id'] ) ? (int) $_GET['id'] : 0;
if ($current_post_id > 0)
{
//Do your thing here.
}
}
return $args;
}
add_filter( 'get_media_item_args', 'get_media_item_args', 10, 1 );

Maybe you can use delete_attachment hook for that. However, this one only affect files that is already attached to post.

Related

Determine which Avada Fusion Builder Elements are being used on a Wordpress site

Is there any way to determine which Fusion Builder Elements are being currently used on a WordPress site?
I have a lot of the elements enabled for a site I'm working on, and I'd like to disable the ones I don't need. Problem is, it's a full site I've taken on from another developer and I REAAAALLY don't want to have to scour the entire site and check for potentially broken elements every time I disable something.
Is this a functionality somewhere within Avada I'm completely missing and I can't find documented anywhere?
I was thinking of writing a tiny plugin that checks the wp_posts table and searching for [fusion_xxxx] elements and displaying a list of used builder elements. Then I can determine which are used throughout the site.
Is this a bad time for any reason?
I wrote a plugin that will run a query on the DB and display used elements and the number of times each is used. Simple, but I think it gets the job done. I very-well might be missing something very obvious about how the info is stored.
This is done in an ajax call, displayed in the browser in a formatted list, etc.
Anywho, here's the part of the plugin that actually gathers the info:
protected function getElementsFromTable($table, $field, &$element_collection)
{
global $wpdb;
$sql = "SELECT * FROM " . $table . " WHERE `" . $field . "` LIKE '%[/fusion_%';";
$results = $wpdb->get_results($sql);
foreach ($results as $item) {
preg_match_all("/\[\/fusion_(.+?)\]/", $item->{$field}, $elements);
// No results found, bail!
if (!count($elements[1])) {
continue;
}
// Store the results
foreach ($elements[1] as $element) {
if (!array_key_exists('fusion_' . $element, $element_collection)) {
$element_collection["fusion_" . $element] = 1;
} else {
$element_collection["fusion_" . $element]++;
}
}
}
}
arsort($element_collection);
Usage:
$this->getElementsFromTable("wp_posts", "post_conent", $element_collection);

Bulk restore revision on all posts on wordpress

Is there a wordpress plugin to restore revisions on multiple posts at once based on date or position?
I have a hacked site in which every post was changed. To make all content clean I would need to restore all posts to a wherever revision was online 5 or 6 days ago.
Thanks in advance!
Honestly, with a hacked site - your best bet is to restore a Database/MySQL backup from a time when it was "clean", or just reverting them manually.
That said, WordPress does let you retrieve revisions using wp_get_post_revisions().
NOTE: This is the plural function, the singular function wp_get_post_revision() get a revision by its ID. Unless you know what the ID of the revision you want is, you don't want this function.The plural function gets all revisions of a post.
Now, before you continue reading - BACK UP YOUR SITE.
Did you back it up?
Make sure you HAVE A BACKUP.
Also, make sure it's a backup that works.
Now, that you have a backup...
Take a look at this function that I came up with, it uses wp_get_post_revisions() in conjunction with wp_update_post(). Again, PLEASE make sure you back up before running this function. It's going to mess with posts and post content, and if it stalls/dies, it could get messy. Use at your own risk.
First, it makes sure you WANT to run this function by visiting https://yoursite.com/?restore_revisions=so_50959583_restore_revisions. It needs that query string to run.
Then it makes sure the current user has admin level privileges.
Then it checks to see if this function has run before, so it doesn't run every time.
Now it runs a standard WP_Query to grab all posts. Note I've ommitted other post types, you can add those in if you want.
Inside the loop, it checks to see if a revision exists, and if so it uses wp_update_post to update the post to the revised post_content.
If it fails here, it will die with a message to prevent setting the flag we checked in the beginning.
Provided it runs smoothly, it sets the so_50959583_restore_revisions_flag option flag so it won't ever run again.
At this point, you should remove the code.
NOTE you could remove the option flag, and set this up as a custom plugin and run the function off of register_activation_hook.
So, here's the beast, best used for illustrative purposes, use it at your own risk.
add_action( 'init', 'so_50959583_restore_revisions' );
function so_50959583_restore_revisions(){
if( isset( $_GET['restore_revisions'] ) && $_GET['restore_revisions'] == 'so_50959583_restore_revisions' ){
if( current_user_can( 'manage_options' ) ){
if( !get_option( 'so_50959583_restore_revisions_flag' ) ){
// This hasn't run before, run it now.
$args = array(
'post_type' => 'post', // Limit to just posts
'posts_per_page' => -1
);
$revision_query = new WP_Query( $args );
if( $revision_query->have_posts() ){
while( $revision_query->have_posts() ){
$revision_query->the_post();
if( $last_revision = array_shift( wp_get_post_revisions( $post->ID ) ) ){
// At least one revision existed.
$reverted_post = array(
'ID' => get_the_ID(), // Update current post in query
'post_content' => $last_revision->post_content // set content to previous content
);
// Update the existing post
if( !wp_update_post( $reverted_post ) ){
wp_die( 'Something went wrong' );
}
}
}
wp_reset_postdata();
}
// Whew, completed!
update_option( 'so_50959583_restore_revisions_flag', true );
}
}
}
}
I would like to stress, again, that your best bet is to keep backups of your database using one of the many available (and ofttimes FREE) plugins, to prevent issues like this from occurring.
Last, if you only have like 20-30 posts, you should just do it by hand. And if you have like 10,000 posts you may need to have this code do it in "chunks" or it may timeout.
Best of luck

Uniquely Identy Wordpress Installation

I am working on an API for wordpress and I am looking for a way to uniquely identify a wordpress installation that is requesting the API. Does anyone know of a install id or unique wordpress blog id? Is that even a thing?
I have written 2 APIs and have worked with several, I stumbled upon this question long time back...
I like to keep the stuff simple... so I use site_url() as identity of the blog, since I'm sure no other installation would run on the same site url so whenever there is an issue to debug, I know site ID is the url.
Saved one extra field in my DB ( If I had ID different, I'd need another field for site url ).
You can also go for complex solutions like using md5 of site_url along with some random generated strings to name a few.
Update
This will generate an ID on activation and save it in the database.
function generate_password($length = 12) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password. = substr($chars, rand(0, strlen($chars) - 1), 1);
}
return $password;
}
function my_plugin_activated() {
$id = generate_password();
add_option('my_plugin_installation_id', $id);
}
register_activation_hook( __FILE__, 'my_plugin_activated' );
Code in my_plugin_activated() is executed only once on activation of plugin ( you can do the same for theme 😉 ), you can, in activation hook itself, make a call to your api and get the site registered in your db.
Hope that helps.

woocommerce add function when admin changes product's attributes

I am relatively new to woocommerce development so I am sorry if this question might be too trivial but I need help.
I need in my application a way to make some checks when an admin makes changes to a product in woocommerce.
For example, I want to create a log file of all the changes that occurred on products. Who made them, when and what was the change (price, inventory, description, etc.).
I understand that there are hooks in woocommerce that I can use. Which ones can help me do something like that?
Use post_updated hook for this purpose, place the following code in your functions.php
function product_update_handler( $id, $before_data, $after_data ) {
if( $before_data->post_type == "product" ) {
$current_user = wp_get_current_user();
error_log( $before_data->post_title ." has been updated by ".$current_user->user_login );
}
}
add_action('post_updated', 'product_update_handler', 0, 3);
you have two product objects ( before update, after update ) with the above hook, you can compare both object and log the changes.

Wordpress Private/Public Posts Security.

I have a quick question to ask.
I've setup a wordpress site with custom theme that has the functionality to set posts "Private/Public" where as you can guess all post marked as private can only be seen by users who are logged in, and public everyone can see.
How I accomplished this was using a custom field "access" and each post can set this custom field to private or public in the edit post screen. Then to display these posts I run a custom loop query with a "is_user_logged_in()" conditional statement. It that statement is true I include all posts with the "access" fields set to both "private/public" and if the statement fails ie the user is not logged in only include posts with "access" set to public. I have used similar loop queries for all single page loops etc.
Now while this works a treat I have concerns over how secure this approach is. Thats were your help comes in. How secure do you think this is? Would it be easy to trick the loop into displaying private post to a user thats not logged in? Can you reccommed a better more secure way of handling private/public posts that can be set by a select number of users on the backend?
ideas much appreciated.
Rob.
maybe I understood all wrong , but -
What You describe is just like the wordpress Default behavior for private posts .
Hence , I do not really understand wh you need a custom field for that .
Custom Fields have the habit of being [ab]used for everything, even if not needed :-)
That being said ,you can use the post_status() function to check for your status
if ( get_post_status ( $ID ) == 'private' )
{
// this is 'private';
}
else
{
// this is public 'public';
}
So you could use
get_post_status ( get_the_ID() )
or if you want to put it at the head of the loop after the the_post() part:
if( get_post_status()=='private' ) continue;
you could wrap it also with is_user_logged_in() if you want .
Point is , there is already a default place in wordpress where "private" is defined . so there is no need to define it elsewhere ( like custom field ).
You can even create your own custom post status with register_post_status() ..
the best way IMHO however , is to filter all the posts on the posts_where
add_filter('posts_where', ' privates_control');
function privates_control($where) {
if( is_admin() ) return $where;
global $wpdb;
return " $where AND {$wpdb->posts}.post_status != 'private' "; // or add your custom status
}
This function simply mofifies the query using the posts_where filter. Codex Link
You can modify it to your needs (add / remove conditions / user levels / user control

Resources