Monday 24 November 2014

Automatically Set the Featured Image

<?php
function autoset_featured() {
          global $post;
          $already_has_thumb = has_post_thumbnail($post->ID);
              if (!$already_has_thumb)  {
              $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
                          if ($attached_image) {
                                foreach ($attached_image as $attachment_id => $attachment) {
                                set_post_thumbnail($post->ID, $attachment_id);
                                }
                           }
                        }
      }
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
?>

Instructions:

This snippet automatically sets the featured image by fetching the first image of the post.

However, if you choose a featured image, that will be displayed instead.

How to Disable plugin updates in wordpress

<?php remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) ); ?>

Instructions:

This snippet simply prevents WordPress from checking if there’s any updates for your plugins.
This could be useful if you’re creating a website for a client, and don’t want them to update their plugins incase you have changed the code in it, or if you’re worried that the update will break the site.





Pagination for Twitter Bootstrap

Instructions:

Insert this into your functions.php. This snippet creates a numbered page navigation menu using Twitter Boostrap native CSS classes. Use in your template files by calling the function page_navi();.

<?php

// Numeric Page Navi
function page_navi($before = '', $after = '') {
global $wpdb, $wp_query;
$request = $wp_query->request;
$posts_per_page = intval(get_query_var('posts_per_page'));
$paged = intval(get_query_var('paged'));
$numposts = $wp_query->found_posts;
$max_page = $wp_query->max_num_pages;
if ( $numposts <= $posts_per_page ) { return; }
if(empty($paged) || $paged == 0) {
$paged = 1;
}
$pages_to_show = 7;
$pages_to_show_minus_1 = $pages_to_show-1;
$half_page_start = floor($pages_to_show_minus_1/2);
$half_page_end = ceil($pages_to_show_minus_1/2);
$start_page = $paged - $half_page_start;
if($start_page <= 0) {
$start_page = 1;
}
$end_page = $paged + $half_page_end;
if(($end_page - $start_page) != $pages_to_show_minus_1) {
$end_page = $start_page + $pages_to_show_minus_1;
}
if($end_page > $max_page) {
$start_page = $max_page - $pages_to_show_minus_1;
$end_page = $max_page;
}
if($start_page <= 0) {
$start_page = 1;
}
echo $before.'<div class="pagination"><ul class="clearfix">'."";
if ($paged > 1) {
$first_page_text = "«";
echo '<li class="prev"><a href="'.get_pagenum_link().'" title="First">'.$first_page_text.'</a></li>';
}
$prevposts = get_previous_posts_link('← Previous');
if($prevposts) { echo '<li>' . $prevposts  . '</li>'; }
else { echo '<li class="disabled"><a href="#">← Previous</a></li>'; }
for($i = $start_page; $i  <= $end_page; $i++) {
if($i == $paged) {
echo '<li class="active"><a href="#">'.$i.'</a></li>';
} else {
echo '<li><a href="'.get_pagenum_link($i).'">'.$i.'</a></li>';
}
}
echo '<li class="">';
next_posts_link('Next →');
echo '</li>';
if ($end_page < $max_page) {
$last_page_text = "»";
echo '<li class="next"><a href="'.get_pagenum_link($max_page).'" title="Last">'.$last_page_text.'</a></li>';
}
echo '</ul></div>'.$after."";
}

?>

Friday 21 November 2014

Working with Databases in Yii framework

This section will describe how to create a new page that displays country data fetched from a database table named country. To achieve this goal, you will configure a database connection, create an Active Record class, define an action, and create a view.
Through this tutorial, you will learn how to:
  • Configure a DB connection
  • Define an Active Record class
  • Query data using the Active Record class
  • Display data in a view in a paginated fashion
Note that in order to finish this section, you should have basic knowledge and experience using databases. In particular, you should know how to create a database, and how to execute SQL statements using a DB client tool.

Preparing the Database

To begin, create a database named yii2basic, from which you will fetch data in your application. You may create an SQLite, MySQL, PostgreSQL, MSSQL or Oracle database, as Yii has built-in support for many database applications. For simplicity, MySQL will be assumed in the following description.
Next, create a table named country in the database, and insert some sample data. You may run the following SQL statements to do so:

CREATE TABLE `country` (
  `code` CHAR(2) NOT NULL PRIMARY KEY,
  `name` CHAR(52) NOT NULL,
  `population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `country` VALUES ('AU','Australia',18886000);
INSERT INTO `country` VALUES ('BR','Brazil',170115000);
INSERT INTO `country` VALUES ('CA','Canada',1147000);
INSERT INTO `country` VALUES ('CN','China',1277558000);
INSERT INTO `country` VALUES ('DE','Germany',82164700);
INSERT INTO `country` VALUES ('FR','France',59225700);
INSERT INTO `country` VALUES ('GB','United Kingdom',59623400);
INSERT INTO `country` VALUES ('IN','India',1013662000);
INSERT INTO `country` VALUES ('RU','Russia',146934000);
INSERT INTO `country` VALUES ('US','United States',278357000);

Configuring a DB Connection

Before proceeding, make sure you have installed both the PDO PHP extension and the PDO driver for the database you are using (e.g. pdo_mysql for MySQL). This is a basic requirement if your application uses a relational database.
With those installed, open the file config/db.php and change the parameters to be correct for your database. By default, the file contains the following:
<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2basic',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];
The config/db.php file is a typical file-based configuration tool. This particular configuration file specifies the parameters needed to create and initialize ayii\db\Connection instance through which you can make SQL queries against the underlying database.
The DB connection configured above can be accessed in the application code via the expression Yii::$app->db.
Info: The config/db.php file will be included by the main application configuration config/web.php, which specifies how the application instance should be initialized. For more information, please refer to the Configurations section.

Creating an Active Record

To represent and fetch the data in the country table, create an Active Record-derived class named Country, and save it in the file models/Country.php.
<?php
namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord{
}
The Country class extends from yii\db\ActiveRecord. You do not need to write any code inside of it! With just the above code, Yii will guess the associated table name from the class name.
Info: If no direct match can be made from the class name to the table name, you can override the yii\db\ActiveRecord::tableName() method to explicitly specify the associated table name.
Using the Country class, you can easily manipulate data in the country table, as shown in these snippets:
use app\models\Country;
// get all rows from the country table and order them by "name"$countries Country::find()->orderBy('name')->all();
// get the row whose primary key is "US"$country Country::findOne('US');
// displays "United States"echo $country->name;
// modifies the country name to be "U.S.A." and save it to database$country->name 'U.S.A.';$country->save();
Info: Active Record is a powerful way to access and manipulate database data in an object-oriented fashion. You may find more detailed information in the Active Record section. Alternatively, you may also interact with a database using a lower-level data accessing method called Data Access Objects.

Creating an Action

To expose the country data to end users, you need to create a new action. Instead of placing the new action in the site controller, like you did in the previous sections, it makes more sense to create a new controller specifically for all actions related to the country data. Name this new controller CountryController, and create an index action in it, as shown in the following.
<?php
namespace app\controllers;

use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;

class CountryController extends Controller{
    public function actionIndex()
    {
        $query Country::find();

        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);

        $countries $query->orderBy('name')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('index', [
            'countries' => $countries,
            'pagination' => $pagination,
        ]);
    }
}
Save the above code in the file controllers/CountryController.php.