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 😉

Changing table columns with migration in Laravel 5 or above

Recently I have started working on a Laravel project and playing with migration for the first time and realized that managing the database with migration, it very easy to handle. In this tutorial, I will explain how to create the migration and how to change columns type.

Subscribe to Blog via Email

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

Let’s create a games table with the migration, so first open your terminal and navigate to your project directory and hit below command:

php artisan make:migration create_games_table

The new migration will be placed in your database/migrations directory. Now open your games migration file and add Schema to your up method:

Schema::create('games', function (Blueprint $table) {
    $table->integer('id', '11')->increments();
    $table->integer('game_id')->nullable();
    $table->integer('title')->nullable();
    $table->string('color')->nullable();
    $table->string('long_title')->nullable();
    $table->string('square_image')->nullable();
    $table->string('circle_image')->nullable();
    $table->string('rectangle_image')->nullable();
    $table->dateTimeTz('created_at')->nullable();
    $table->dateTime('updated_at')->nullable();
    $table->dateTime('deleted_at')->nullable();
});

Run migration command to generate your games table:

php artisan migrate

Now after creating a table, I realized that I have done a mistake in the title field and I used the title as an integer type and it must have string type so now what to do. Well, it’s very easy to replace the type with the migration.

Create a new migration and add Schema to your up method:

Schema::table('games', function($table)
{
    $table->string('title')->change();
});

You just need to add change() function at the end of the chain and it will correct your type.

If you are getting below error after running migration don’t afraid.

[RuntimeException]                                                                   
Changing columns for table "games" requires Doctrine DBAL; install "doctrine/dbal".

You must install doctrine/dbal so type composer require doctrine/dbal in your terminal.

Happy Coding 😉

How to change pre-installed PHP version to MAMP in Mac/OSX

If you are using Mac OSX for the first time and switched from the windows environment and want to develop some cool web-based application then you need to install MAMP which is absolutely free. After installing MAMP on your local environment you need to add the MAMP version of PHP to the PATH variable.

Subscribe to Blog via Email

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

Instructions to Change PHP Installation:

First, Let’s find out what version of PHP we’re running (To find out if it’s the default version). To do that, within the terminal, run this command:

which php

This should output the path to the default PHP install which comes pre-installed by Mac OSX, by default it has to be (Assuming you’ve not changed it before):

/usr/bin/php

Now, we just need to swap this over to the PHP that is installed with MAMP, which is located at

/Applications/MAMP/bin/php/php7.1.6/bin

To do this, we need to edit the .bash_profile and add the MAMP version of PHP to the PATH variable.

Within the Terminal, run

vim ~/.bash_profile

Type i and then paste the following at the top of the file:

export PATH=/Applications/MAMP/bin/php/php7.1.6/bin:$PATH

Hit esc, Type :wq, and hit enter.

In Terminal, run

source ~/.bash_profile

Now type in which php again and look for the updated string. If everything was successful, It should output the new path to the MAMP PHP install.

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 😉

How to upload multiple images with jQuery ajax

This tutorial is very useful for those who just started developing in the PHP field and it’s a very common script. You can find lots of similar scripts in the world wide web, but I am posting for you and I hope this code becomes helpful to your project.

Subscribe to Blog via Email

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

Step 1:

Follow this folder structure.

css

-- style.css

js

-- jquery-1.8.3

uploads

ajax.php 
index.php 
loader.gif

 Step 2:

Include bellow jQuery library and stylesheet in your index.php file.

<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>

Step 3:

Add bellow ajax + html code to your index.php file.

<script type="text/javascript">
    $(window).load(function(){
        $("form[name='uploadfrm']").submit(function(event){
            event.preventDefault();
            $("#loading").show();
            
            var formData = new FormData($(this)[0]);
            console.log(formData);
            $.ajax({
                url: "ajax.php",
                type: "POST",
                data: formData,
                async: false,
                success: function(msg){
                    $("#loading").hide();
                    $('#uploadfrm')[0].reset(); // Reset form data
                },
                cache: false,
                contentType: false,
                processData: false
            });
        });            
    });
</script>

<form name="uploadfrm" id="uploadfrm" method="post" enctype="multipart/form-data" action="ajax.php">
    <div>
        <label>Upload your images:</label>
    </div> 
            
    <div id="loading" class="none">
        <img src="loader.gif" alt="Loading...."/>
    </div>
     
    <div>
        <input type="file" name="images[]" id="photoimg" multiple="true" accept="image/*" />
    </div>
    
    <div>
        <input type="submit" name="upload" id="upload" value="Submit your images" />
    </div>
</form>

 Step 4:

Create ajax.php file for upload files.

<?php
    $timestamp = time(); // Current timestamp
    $location = "uploads/"; // Location to store image
    $allow = array("jpg", "jpeg", "png"); // Allow certain filetypes on upload
    $images = $_FILES["images"]["name"]; // Get only image names from array
    $tmp_name = $_FILES["images"]["tmp_name"];

    for($i=0; $i<count($images); $i++){
        $ext = strtolower(pathinfo($images[$i], PATHINFO_EXTENSION));
        if(in_array($ext, $allow)){
            $image = strtolower($images[$i]); // Create image name with lower case
            move_uploaded_file($tmp_name[$i], $location.$timestamp.$image); // The file has been moved correctly
        }else{
            echo "Error This file ". $images[$i] ." is not allowed.";
            echo "<br />";
        }
    }
?>

Keep visiting for new stuff and give your feedback.

Happy Coding 😉