Replace old to new url in the WordPress database

If you are new in WordPress development and working on a client project then one thing you have to take note is that whenever you deploy your WordPress project to client-server you have to replace your site URL from local to live and the same thing will apply, If you migrate from one to another domain. If you forgot to change URL then it will redirect to the old URL and that needs to take care of it.

Another way you can avoid this problem by creating a virtual host in your local server with a live domain.

replace old to new url in the wordpress database

So how to replace old to new URL in the WordPress database? Well, it’s very easy. You just have to replace your old URL with the new URL so follow the below steps.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Step 1:

If you have already uploaded the database to the server, then go to your phpMyAdmin and open your database.

Step 2:

Copy the below code and replace your old URL with http://www.oldurl.in and do the same for the new URL.

UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldurl.in', 'https://www.mananpatel.in') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://www.oldurl.in','https://www.mananpatel.in');

UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldurl.in', 'https://www.mananpatel.in');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.oldurl.in','https://www.mananpatel.in');

After replacing your old & new URL, go to the SQL section in your phpMyAdmin and past your SQL queries and hit the Go button.

After hitting the Go button, SQL queries will replace all instances of old URLs to new URLs. For example, If your current WordPress address is http://www.oldurl.in, it will be changed to https://www.mananpatel.in.

IMPORTANT! Sometimes table prefix can be different than wp_. If you get error messages saying that tables wp_optionswp_postswp_posts and wp_postmeta cannot be found, check table prefix and update SQL query code. You can see table prefix on the left side of phpMyAdmin, under your WordPress database:

Step 3:

If the query was executed successfully, then you will see a green success message with the number of records is affected.

Keep visiting for new stuff and give your feedback.

Happy Coding 😉

How to Remove the WordPress Version Number

By default WordPress, the version number is enabled and show in the code of WordPress site installation. Generally, there is no need to remove the version number.

Maybe someone doesn’t want to reveal the version number of the WP site. It is generally needed when you don’t update WordPress when the update available.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Using the below code version number from WordPress front-end code can be removed. Add this code in functions.php of your active theme.

// Remove WordPress Version number
function remove_wordpress_version_number() {
    return '';
}
add_filter('the_generator', 'remove_wordpress_version_number');

Happy Coding 😉

Solving WordPress Asking for FTP Credentials When Installing Plugins or Themes

Most web hosting is configured to automate installing themes or plugins. On some hosting WordPress ask for FTP details either to update or install a theme or Plugin.

To fix this issue we can enter our FTP credentials in the wp-config.php file so that we don’t have to enter it every time we update a plugin.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

It also helps in the new automatic update feature introduced by WordPress.

Enter the following code in the wp-config.php file:

define('FTP_USER', 'username');
define('FTP_PASS', 'password');
define('FTP_HOST', 'ftp.mananpatel.in:21');

Where

  • username is ftp username.
  • password is ftp password.
  • ftp.mananpatel.in is ftp hostname and 21 is port number.

Alternatively, We can also override default file and directory permission by entering following lines in wp-config.php

define( 'FS_CHMOD_FILE', 0644 );
define( 'FS_CHMOD_DIR', 0755 );
Where
  • FS_CHMOD_FILE is file permission &
  • FS_CHMOD_DIR is directory permission.

Happy Coding 😉

WordPress Permalinks Not Working on Ubuntu 14.04

Today I have installed Ubuntu 14.04 for web development and installed fresh WordPress but after clicking on any pages, it takes me to the apache 404 page so how to fix this issue?

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

First, open your terminal and follow these steps:

Step 1:

Activate the mod_rewrite module

sudo a2enmod rewrite

Step 2:

Restart the apache server

sudo service apache2 restart

Step 3:

To use mod_rewrite from within .htaccess files (which is a very common use case), edit the default VirtualHost with

sudo nano /etc/apache2/sites-available/000-default.conf

Step 4:

Search for DocumentRoot /var/www/html” and add the following lines directly below:

<Directory "/var/www/html">
    AllowOverride All
</Directory>

Save and exit the nano editor via CTRL-X, “y” and ENTER.

Step 5:

Restart the server again:

sudo service apache2 restart

Step 6:

Check if mod_rewrite is installed correctly, check your phpinfo() output. It should have this in it:

mod-rewrite-apache

Keep visiting for new stuff and give your feedback.

Happy Coding 😉

WordPress custom post type pagination

The last couple of days have been very hectic for me for finding a solution regarding how to write code for multiple meta queries for custom fields, and as I am a great fan of ACF(Advanced Custom Fields) I prefer using ACF because it’s very easy to create fields and display values on front-end side.

In my last project, my task was to display results based on the search with pagination. I had so much googled and posted a question on Stackoverflow and WordPress forums but did not get any proper answer. Then I decided to use $wpdb SQL query.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Why I did not choose meta_query? Because when I pass more than 3 keys and value to search, my page kept loading and loading.

Before I explain more about this article, here I am posting my meta_query code for readers. If you know how to fix this issue please share your modified code in comments and I will add in my next post.

<?php   
    $args = array(
        'post_type' => 'book',
        'post_status'   => 'publish',
        'order' => 'DESC',
        'orderby' => 'date',
        'posts_per_page' => -1,
        'meta_query' => array(
        'relation' => 'OR',
            array(
                'key' => 'type',
                'value' => 'Sample 1',
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'type',
                'value' => 'Sample 2',
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'type',
                'value' => 'Sample 3',
                'compare' => 'LIKE'
            ),
            array(
                'key' => 'type',
                'value' => 'Sample 4',
                'compare' => 'LIKE'
            )
        )
    );
    $query = new WP_Query( $args );
?>

<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

    <h1><a href="<?php the_permalink(); ?>"><?php echo the_title(); ?></a></h1>

<?php endwhile; endif; wp_reset_postdata(); ?>

Finally, I found the solution from StackOverflow and would like to thanks everyone who posted the answer. Now I am presenting that code with little bit modification by me. In this code, your task is only to change the SQL query to your query.

<?php      
    global $wpdb, $paged, $max_num_pages;

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $post_per_page = 3;
    $offset = ($paged - 1)*$post_per_page;

    $query_spicy = "SELECT wposts.* FROM $wpdb->posts wposts WHERE wposts.post_status = 'publish' AND wposts.post_type = 'villa' ORDER BY wposts.post_date DESC";

    //QUERY THE POSTS WITH PAGINATION
    $spicy = $query_spicy . " LIMIT ".$offset.", ".$post_per_page."; ";

    $spicy_results = $wpdb->get_results( $spicy, OBJECT);

    //RUN QUERY TO COUNT THE RESULT LATER
    $total_result = $wpdb->get_results( $query_spicy, OBJECT );

    $total_spicy_post = count($total_result);
    $max_num_pages = ceil( $total_spicy_post / $post_per_page );
?>

<div class="result-count">
        <?php 
            if($total_spicy_post >= 1){
                ?> Showing all <?php echo $total_spicy_post; ?> results <?php
            }else{
                ?> No records found. <?php
            }
        ?>
</div>

<?php
    global $post;
    foreach ($spicy_results as $post) :
        setup_postdata($post);
?>
    <h1><a href="<?php the_permalink(); ?>"><?php echo the_title(); ?></a></h1> 
<?php
    endforeach;
?>

<?php
    global $wp_rewrite, $wp_query, $max_page, $page;
    $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

    $pagination = array(
        'base' => @add_query_arg('page','%#%'),
        'format' => '',
        'total' => $max_num_pages,
        'current' => $current,
        'prev_text' => __('PREV'),
        'next_text' => __('NEXT'),
        'end_size' => 1,
        'mid_size' => 2,
        'show_all' => false,
        'type' => 'list'
    );

    if ( $wp_rewrite->using_permalinks() )
           $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

    if ( !empty( $wp_query->query_vars['s'] ) )
            $pagination['add_args'] = array( 's' => get_query_var( 's' ) );

    echo paginate_links( $pagination );
?>

Keep visiting for new stuff and give your feedback.

Happy Coding 😉

How to use wp_mail with WordPress

WordPress has its own email functionality, which calls wp_mail for sending emails. WordPress wp_mail function is allowing you the same functionality as PHP is giving to you so let’s try and use it.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Usage:

<?php wp_mail( $to, $subject, $message, $headers, $attachments ); ?>
  • $to: (string or array) (required) The intended recipient(s). Multiple recipients may be specified using an array or a comma-separated string. Default: None
  • $subject: (string) (required) The subject of the message. Default: None
  • $message: (string) (required) Message content. Default: None
  • $headers: (string or array) (optional) Mail headers to send with the message. For the string version, each header line (beginning with From:, Cc:, etc.) is delimited with a newline (“\r\n”) (advanced) Default: Empty
  • $attachments: (string or array) (optional) Files to attach: a single filename, an array of filenames, or a newline-delimited string list of multiple filenames. (advanced) Default: Empty

Examples of wp_mail():

Sending an email with simple way:

<?php wp_mail( 'somebody@example.com', 'The subject', 'The message' ); ?>

Sending an email to multiple recipients:

<?php
    $multiple_to_recipients = array(
        'somebody@example.com',
        'somebodyelse@example.com'
    );
    $subject = 'The subject';
    $message = 'The message';
    
    $headers[] = 'From: webmaster <webmaster@example.com>';
    $headers[] = 'Cc: somebody <somebody@example.com>';
    $headers[] = 'Cc: somebodyelse@example.com'; // note you can just use a simple email address
    
    wp_mail( $multiple_to_recipients, $subject, $message, $headers );
?>

Sending an email with the attachment:

<?php
    $to  = 'somebody@example.com';
    $subject = 'The subject';
    $message = 'The message';
    
    $attachments = array( WP_CONTENT_DIR . '/uploads/2013/07/wallpaper-2407801-150x150.jpg' );
    $headers[] = 'From: webmaster <webmaster@example.com>';
    add_filter( 'wp_mail_content_type', 'my_custom_email_content_type' );
    return wp_mail( $to, $subject, $message, $headers, $attachments );
    
    function my_custom_email_content_type() {
        return 'text/html';
    }
?>

Keep visiting for new stuff and give your feedback.

Happy Coding 😉