PHP WordPress Print List Of Categories And Their Information

PHP WordPress Print List Of Categories And Their Information

A quick copy-paste function to print all your categories and dump some of their crucial information out.

function print_all_categories_html()
{
    $categories = get_categories( array(
        'orderby' => 'name',
        'order'   => 'ASC'
    ) );
     
    foreach( $categories as $category ) {
        $category_link = sprintf( 
            '<a href="%1$s" alt="%2$s">%3$s</a>',
            esc_url( get_category_link( $category->term_id ) ),
            esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
            esc_html( $category->name )
        );
         
        echo '<p>' . sprintf( esc_html__( 'Category: %s', 'textdomain' ), $category_link ) . '</p> ';
        echo '<p>' . sprintf( esc_html__( 'Description: %s', 'textdomain' ), $category->description ) . '</p>';
        echo '<p>' . sprintf( esc_html__( 'Post Count: %s', 'textdomain' ), $category->count ) . '</p>';
    } 
    
    return $categories;
}

 

Enjoyed the content ? Share it with your friends !

PHP Prevent Multiple Instances Of The Same Script

PHP Prevent Multiple Instances Of The Same Script

Using flock, you are able to lock a file and hence only allow one instance of your script to run. If your script terminates abruptly, or you fail to release the lock, the OS will automatically release the locks when the process holding them terminates. Hence, this is a much better alternative to using for example, a text file or database record.

<?php

$lock_file = fopen('path/to/yourlock.pid', 'c');
$got_lock = flock($lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($lock_file === false || (!$got_lock && !$wouldblock)) {
    throw new Exception(
        "Unexpected error opening or locking lock file. Perhaps you " .
        "don't  have permission to write to the lock file or its " .
        "containing directory?"
    );
}
else if (!$got_lock && $wouldblock) {
    exit("Another instance is already running; terminating.\n");
}

// Lock acquired; let's write our PID to the lock file for the convenience
// of humans who may wish to terminate the script.
ftruncate($lock_file, 0);
fwrite($lock_file, getmypid() . "\n");

/*
    The main body of your script goes here.
*/
echo "Hello, world!";

// All done; we blank the PID file and explicitly release the lock 
// (although this should be unnecessary) before terminating.
ftruncate($lock_file, 0);
flock($lock_file, LOCK_UN);

 

Enjoyed the content ? Share it with your friends !

PHP WordPress Delete Duplicate Post By Title And Category

PHP WordPress Delete Duplicate Post By Title And Category

I have been looking online for a code solution that is able to check through specific categories for duplicate posts and never been able to found a solution good enough for me. Solutions online were slow and memory-consuming which was a major reason why I couldn’t use them. So I wrote my own.

For the code below to work, you need to ensure that you sort your posts in alphabetical order. The logic is that you have a inner-loop that checks from the given post (Post A) till the last post for any duplicate titles. The logic at the same time ensures that Post A will never be deleted, ensuring you have at least 1 copy of the post.

$args = [
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'category_name' => $category->name,
    'orderby'   => 'post_title', 
    'order' => 'ASC',
    'post_per_page' => -1,
    'nopaging' => true,
];
$my_query = new WP_Query( $args );
$posts = $my_query->posts;

    $num_of_posts = count($posts);
    echo "category : {$category->name} <br/>";
    echo "num_of_posts : {$num_of_posts} <br/>";
    
    for($j = 0; $j < $num_of_posts; $j++)
    {
        $post = $posts[$j]; // this post will be the post that doesnt get deleted, if any duplicates exist down the line //
        $current_title = $post->post_title;
        
        for($k = $j+1; $k < $num_of_posts; $k++)
        {
            $next_post = $posts[$k];
            $next_title = $next_post->post_title;
            $next_id = $next_post->ID;
            
            if( strcmp($current_title, $next_title) == 0 ) {
                echo "Duplicate for {$current_title} with ID {$next_id} will be deleted <br/>";
                wp_delete_post($next_id, false); // move to trash first
            }
        }
    }	
}

 

Enjoyed the content ? Share it with your friends !

PHP Quick Function For Asynchronous Multi Curl

PHP Quick Function For Asynchronous Multi Curl

If you are here, it probably means that you have a problem Рyou have a bunch of URLs that you need to cURL, but doing it linearly (one by one) is too slow. This is where curl_multi_init comes in. It is the asynchronous version of curl and it will help you to save lots of time (by that i mean like 80-90%)

So anyway, below is a quick function for you to use. Feel free to modify it according to your needs.

function get_content_of_urls($urls)
{
    // array of curl handles
    $multi_curl = array();
    // data to be returned
    $results = array();
    // init multi handle
    $mh = curl_multi_init();
    $i = 0;
    foreach ($urls as $url) 
    {	
        $multi_curl[$i] = curl_init();
        curl_setopt($multi_curl[$i], CURLOPT_URL,$url);	
        curl_setopt($multi_curl[$i], CURLOPT_HEADER, 0); 
        curl_setopt($multi_curl[$i], CURLOPT_RETURNTRANSFER,1);
        curl_multi_add_handle($mh, $multi_curl[$i]);
        $i++;
    }
    $index=null;
    do {
        curl_multi_exec($mh,$index);
    } while($index > 0);
    // get content and remove handles
    foreach($multi_curl as $k => $ch) {
        $results[$k] = curl_multi_getcontent($ch);
        curl_multi_remove_handle($mh, $ch);
    }
    return $results;
}

If you require any assistance, feel free to let me know in the comments below.

Enjoyed the content ? Share it with your friends !

HTML CSS Code To Put Your Element In Any Of The 9 Quadrants

HTML CSS Code To Put Your Element In Any Of The 9 Quadrants

Using the css below, you can put any element <div>, <img>, and so on in any of the 9 quadrants

  • top left, top middle, top right
  • middle left, middle, middle right
  • bottom left, bottom middle, bottom right
<style>
.topleft {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
}
.topmiddle {
   position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:0 auto;
}
.topright {
   position:absolute;
    top:0;
    right:0;
    bottom:0;
    margin:0 auto;
}


.middle {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin: auto;
}
.middleleft {
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    margin: auto;
}
.middleright {
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    margin: auto;
}

.bottomleft {
    position:absolute;
    left:0;
    bottom:0;
    margin:0 auto;
}
.bottommiddle {
    position:absolute;
    left:0;
    right:0;
    bottom:0;
    margin:0 auto;
}
.bottomright {
    position:absolute;
    right:0;
    bottom:0;
    margin:0 auto;
}
</style>

Example :

<div class="middleright" style="max-height:450px;max-width:300px;">
    <img src="https://image.shutterstock.com/image-photo/beautiful-water-drop-on-dandelion-260nw-789676552.jpg">
</div>

 

Enjoyed the content ? Share it with your friends !