PHP WordPress Delete All Posts with thumbnail image permanently

Delete all image, meta data and post permanently.


# delete all posts
$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1,
    'post_status' => 'any'
);
$posts = get_posts($args);
foreach ($posts as $post) {
    # delete post thumbnail
    $thumbnail_id = get_post_thumbnail_id($post->ID);
    if ($thumbnail_id) wp_delete_attachment($thumbnail_id, true);
    wp_delete_post($post->ID, true);
}

PHP IMAGE RESIZE FUNCTION FOR ALL FORMATS

You can use this function to resize and change quality of image for jpg, png, gif, bmp formats.

  • php image resize function for all image formats
  • parameters: image_path (required), new_width (optional), new_height (optional), quality (optional)
  • image_path: path to the image file
  • new_image_path: path to the resized image file
  • resize_x: resize by width
  • resize_y: resize by height
  • quality: JPEG quality (0-100)
  • returns boolean
# php image resize function for all image formats

function resize_image($image_path,$new_image_path,$resize_x,$resize_y,$quality) {
 
    // jpeg, png, gif or bmp?
    $ext = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));
    
    // image create function
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $image = imagecreatefromjpeg($image_path);
            break;
        case 'png':
            $image = imagecreatefrompng($image_path);
            break;
        case 'gif':
            $image = imagecreatefromgif($image_path);
            break;
        case 'bmp':
            $image = imagecreatefrombmp($image_path);
            break;
        default:
            return false;
    }
    
    // resize
    $resized = imagecreatetruecolor($resize_x, $resize_y);
    imagecopyresampled($resized, $image, 0, 0, 0, 0, $resize_x, $resize_y, imagesx($image), imagesy($image));
    
    // output
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($resized, $new_image_path, $quality);
            break;
        case 'png':
            imagepng($resized, $new_image_path);
            break;
        case 'gif':
            imagegif($resized, $new_image_path);
            break;
        case 'bmp':
            imagewbmp($resized, $new_image_path);
            break;
    }
    
    // clear resources
    imagedestroy($image);
    imagedestroy($resized);
    
    return true;
}

How to resize an image in php

Woocommerce add to cart hook to dont allow user to add cart less than “_min_quantity” product meta

woocommerce add to cart hook to dont allow user to add cart less than "_min_quantity" product meta for wordpress

min quantity plugin example

If you want to dont allow user to add cart less than pack you can use this hook for it.

You can add this hook and function to functions.php of your theme or plugin.

This hook uses woocommerce_add_to_cart


add_action(
    'woocommerce_add_to_cart',
    'gc_add_to_cart_validation',
    10,
    6
);

function gc_add_to_cart_validation($product_id, $quantity, $variation_id = '', $variation = '', $cart_item_data = array())
{
    $product = wc_get_product($product_id);

    if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        foreach ($variations as $variation) {
            if ($variation["attributes"]["attribute_pa_produkt-einheit"] == "kolli") {
                $min_quantity = get_post_meta($product_id, "_min_quantity", true);
                if ($quantity < $min_quantity) {
                    wc_add_notice(
                        sprintf(
                            __('You can not add less than %s kolli', 'woocommerce'),
                            $min_quantity
                        ),
                        'error'
                    );
                }
            }
        }
    } else {
        $min_quantity = get_post_meta($product_id, "_min_quantity", true);
        if ($quantity < $min_quantity) {
            wc_add_notice(
                sprintf(
                    __('You can not add less than %s kolli', 'woocommerce'),
                    $min_quantity
                ),
                'error'
            );
        }
    }
}

PHP CACHE EXAMPLE WITH TIMEOUT

<?php
// this is our base interface for cache class

interface CacheDriver
{
    public function get($key, $timeout = null, callable $callback = null);

    public function set($key, $value, $timeout = null);

    public function delete($key);

    public function deleteAll();

    public function deleteExpired();

    public function deleteExpiredByTimeout($timeout);

    public function deleteExpiredByKey($key);

    public function deleteExpiredByKeyTimeout($key, $timeout);
}


/**
 * Class Cache
 * static cache
 * save data in file
 * set file names as md5
 * use directory structure to save data
 * define timeout limit for cache files and if exceeded delete file
 * store cache as serialized time and data array
 *
 */
class FileCache implements CacheDriver
{

    /**
     * @var string
     */
    private static $cache_dir = 'cache/';

    /**
     * @var int
     */
    private static $cache_timeout = 3600;

    /**
     * @var string
     */
    private static $cache_ext = '.cache';

    /**
     * @param $key
     * @param int $timeout
     * @param callable $callback
     * @return bool
     * @description get data from cache by key
     */
    public function get($key, $timeout = null, callable $callback = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] < $timeout) {
                return $data['data'];
            }
        }

        if (is_callable($callback)) {
            $data = call_user_func($callback);
            $this->set($key, $data, $timeout);
            return $data;
        }

        unlink($file);

        return false;
    }

    /**
     * @param $key
     * @param $data
     * @return bool
     * @description set data and timeout to cache by key
     */

    public function set($key, $data, $timeout = null)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        $data = array('time' => time(), 'data' => $data);
        file_put_contents($file, serialize($data));
        return true;
    }

    /**
     * @param $key
     * @return bool
     * @description delete cache by key
     */
    public function delete($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            unlink($file);
            return true;
        }
        return false;
    }

    /**
     * @return bool
     * @description delete all cache
     */
    public function deleteAll()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            unlink($file);
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpired()
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;

    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByTimeout($timeout)
    {
        $files = glob(self::$cache_dir . '*' . self::$cache_ext);
        foreach ($files as $file) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */

    public function deleteExpiredByKey($key)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > self::$cache_timeout) {
                unlink($file);
            }
        }
        return true;
    }

    /**
     * @return bool
     * @description delete expired cache
     */
    public function deleteExpiredByKeyTimeout($key, $timeout)
    {
        $file = self::$cache_dir . $key . self::$cache_ext;
        if (file_exists($file)) {
            $data = unserialize(file_get_contents($file));
            if (time() - $data['time'] > $timeout) {
                unlink($file);
            }
        }
        return true;
    }
}


class Cache extends FileCache
{
    public function __construct()
    {
        parent::__construct();
    }
}

$cache = new Cache();
$result = $cache->get("test", DEFAULT_CACHE_TIMEOUT, function () {
    return "data of cache";
});

PHP Woocommerce Delete Products With Variations and images

Delete products with all information

<?php


include __DIR__ . "/../../wp-load.php";

#delete woocommerce products from array with all images
$products = [1,2,3]; // product id's
foreach ($products as $product) {

    $product_sku = $product;
    $product_id = wc_get_product_id_by_sku($product_sku);

    if(!$product_id){
        echo "Product with SKU: " . $product_sku . " not found.<br>\n";
        continue;
    }

    #delete product variations by product id
    $variations = get_children(array(
        'post_parent' => $product_id,
        'post_type' => 'product_variation',
        'fields' => 'ids'
    ));

    foreach ($variations as $variation_id) {
        wp_delete_post($variation_id, true);
    }

    #delete product images
    $product_images = get_post_meta($product_id, '_product_image_gallery', true);
    if($product_images){
        $product_image_gallery = explode(',', $product_images);
        foreach ($product_image_gallery as $image_id) {
            wp_delete_attachment($image_id, true);
        }
    }

    #delete product
    if ($product_id) {
        wp_delete_post($product_id, true);
        echo "Product deleted: " . $product_sku . " " . $product_id . "<br>\n";
    }

}

PHP XML DATABASE EXAMPLE

This class made with github copilot

  • Search in xml by value and key
  • Add row in xml
  • Read xml from file
<?php

# xml based static database class for the application
# store the lines in xml file
# read and write arrays as xml
class XMLDatabase
{
    private $xml = null;

    public function __construct($xml_file)
    {
        $this->xml_file = $xml_file;
        $this->xml = simplexml_load_file($this->xml_file);
    }

    public function write($array){
        $xml = new SimpleXMLElement('<root/>');
        array_walk_recursive($array, array($this->xml, 'addChild'));
        $xml->asXML($this->xml_file);
    }

    public function read(){
        return json_decode(json_encode($this->xml), true);
    }

    # add line to xml file
    public function addLine($line){
        $this->xml->addChild('line', $line);
    }

    # save xml file
    public function save(){
        $this->xml->asXML($this->xml_file);
    }

    # search for a specific value in the xml file and return all the lines that contain it in array
    public function search($value){
        $result = array();
        foreach($this->xml->children() as $child){
            if(strpos($child, $value) !== false){
                array_push($result, $child);
            }
        }
        return $result;
    }

    # search for a spesific value in the xml file and return the line that contains it
    public function search_one($value){
        foreach( $this->xml->children() as $child){
            if(strpos($child, $value) !== false){
                return $child;
            }
        }
        return null;
    }

    # search for a spesfic value and key in the xml file and return all the lines that contain it in array
    public function search_key($value, $key){
        $result = array();
        foreach( $this->xml->children() as $child){
            if(strpos($child->$key, $value) !== false){
                array_push($result, $child);
            }
        }
        return $result;
    }

    # search for a spesfic value and key in the xml file and return all the line that contain it
    public function search_key_value($value, $key){
        $result = array();
        foreach( $this->xml->children() as $child){
            if(strpos($child->$key, $value) !== false){
                $result = $child;
            }
        }
        return $result;
    }


}

PHP FTP Connection and File Download Upload Example

PHP FTP File Download Example

// define some variables

$server_file = 'file.xml';
$ftp_server = "server_address";
$ftp_user_name = "user";
$ftp_user_pass = "pass";

$data = file_get_contents('ftp://'.$ftp_user_name.':'.$ftp_user_pass.'@'.$ftp_server.'/' . $server_file);

// put downloaded content to a file
file_put_contents(__DIR__ . "/data.xml",$data);

PHP SCANDIR() Examples List all files and directories in a directory , only files , only directories

In this article you will learn:

How to List All Files and Directories Requiresively and get as an arrayy

List just all files Requiresively in PHP

List all files and directories in current directory

List just files in current directory PHP CANDIR()

just directories in PHP CANDIR()

How to List All Files and Directories Requiresively and get as an array

Notice : Returns all files and directories widthin a directory REQUIRESIVELY.

<?php

function scan_dir($directory,&$result_array = []){

    $files = array_diff(scandir($directory), array('.', '..'));

    foreach ($files as $file) {

        $result_array[] = $directory . "/" . $file;

        if (is_dir($directory . "/" . $file)) {
            scan_dir($directory . "/" . $file , $result_array);
        }
        
    }

}


$result_array = [];

scan_dir(__DIR__ , $result_array);

print_r($result_array);


List only all files Requiresively in PHP





<?php

function scan_dir($directory,&$result_array = []){

    $files = array_diff(scandir($directory), array('.', '..'));

    foreach ($files as $file) {

        if (is_dir($directory . "/" . $file)) {
            scan_dir($directory . "/" . $file , $result_array);
        }else{
            $result_array[] = $directory . "/" . $file;
        }
        
    }

}


$result_array = [];

scan_dir(__DIR__ , $result_array);

print_r($result_array);




List all files and directories in current directory

<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    echo __DIR__ . "/" . $file;
}

List just files in current directory PHP CANDIR()



<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    //jump if it is not a file
    if(!is_file(__DIR__ . "/" . $file)) continue;
    echo __DIR__ . "/" . $file;
}


List just directories in PHP CANDIR()



<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    //jump if it is not a file
    if(is_file(__DIR__ . "/" . $file)) continue;
    echo __DIR__ . "/" . $file;
}