Codeigniter Recusrsive Category List

Conside categories table with structure is id, name, parent_id.  A category can have many subcategories and a subcategory can have many sub-sub categories.

This is the code to get all categories and their subcategories.


$tree = $this->get_category_by_parent(0);

public function get_category_by_parent($parent_id = 0) {
		  $categories = array();
		  $this->db->from('categories');
		  $this->db->where('parent_id', $parent_id);
		  $result = $this->db->get()->result();
		  foreach ($result as $mainCategory) {
		    $category = array();
		    $category['id'] = $mainCategory->id;
		    $category['name'] = $mainCategory->name;
		    $category['parent_id'] = $mainCategory->parent_id;
		    $category['sub_categories'] = $this->get_category_by_parent($category['id']);
		    $categories[$mainCategory->id] = $category;
		  }
		  return $categories;
}

Category-subcategory Dropdownlist,
category_model.php:


public function fetchCategoryTree($parent_id = 0, $spacing = '', $user_tree_array = '') {
 
      if (!is_array($user_tree_array))
        $user_tree_array = array();

      $this->db->where('parent_id', $parent_id);
      $query = $this->db->get('categories');
      $result = $query->result();
      foreach ($result as $mainCategory) {
        $user_tree_array[] = array("id" => $mainCategory->id, "name" => $spacing . $mainCategory->name);
          $user_tree_array = $this->fetchCategoryTree($mainCategory->id, $spacing . '  ', $user_tree_array);
      }
      return $user_tree_array;
    }

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$categoryList = $this->category_model->fetchCategoryTree();
?>
<select>
<?php foreach($categoryList as $cl) { ?>
<option value=”<?php echo $cl[“id”] ?>”><?php echo $cl[“name”]; ?></option>
<?php } ?>
</select>

Category-SubCategory Listing,
category_model.php:

function fetchCategoryTreeList($parent_id = 0, $user_tree_array = ”) {
if (!is_array($user_tree_array))
$user_tree_array = array();

$this->db->where(‘parent_id’, $parent_id);
$query = $this->db->get(‘categories’);
$result = $query->result();
$user_tree_array[] = “<ul>”;
foreach ($result as $mainCategory) {
$user_tree_array[] = “<li>”. $mainCategory->name.”</li>”;
$user_tree_array = $this->fetchCategoryTreeList($mainCategory->id, $user_tree_array);
}
$user_tree_array[] = “</ul>”;

return $user_tree_array;
}

views/category/index.php:

<?php
$this->load->model(‘category_model’);

$res = $this->category_model->fetchCategoryTreeList();
foreach ($res as $r) {
echo $r;
}

?>

PHP CodeSniffer – Coding Standard Tool

Install PHP-Coding-Standards

> pear install PHP_CodeSniffer-2.8.1

Install WordPress-Coding-Standards

> cd /var/www/html
> git clone -b master https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards.git wpcs
> phpcs –config-set installed_paths /var/www/html/wpcs

Install Codeigniter-Coding-Standards

> git clone https://github.com/thomas-ernest/CodeIgniter-for-PHP_CodeSniffer.git
> ant

or

> ant -Dphpcs.dir=”/usr/share/php/PHP/CodeSniffer”

Check Supported standards

> phpcs -i

Uninstall PHP-Coding-Standards

> pear uninstall PHP_CodeSniffer-2.8.1

Check Errors and Warnings

> phpcs file.php

Autofix Errors

> phpcbf file.php

Alphabetic Pagination in CakePHP

Open your controller file,

function index($page = 1) {
 $alphabets = range('A', 'Z');
 $alphagroups = array_chunk($alphabets,3);
 $alphagroups[] = array(0,9);
 $cur_alpha = (isset($page))?($page-1):0;
 if($cur_alpha >= 9){
  $reg_cond = '0123456789';
 } else {
  $reg_cond = trim(implode('', $alphagroups[$cur_alpha]));
 }
 $this->set('cur_alpha', $cur_alpha);
 $this->set('alphas', $alphagroups);
 $total = $this->Vendor->find('count');
 $this->set('total', $total);
 $this->Vendor->recursive = -1;
 $vendors = $this->Vendor->find('all', array(
  'conditions' => array('Vendor.name REGEXP' => '^['.$reg_cond.']')
));
 $this->set('vendors', $vendors);
}

Open index.ctp

foreach ($alphas as $key=>$alpha):
 $alphacode = implode("-",$alpha);
 if($key == $cur_alpha):
    echo $alphacode;
 else: 
    echo $html->link(__($alphacode, true), array('action'=>'index', $key+1));
 endif;
endforeach;

Categories followed by their subcategories in dropdown – Yii2.0

For Example

Parent1
__Child1-Parent1
__Child2-Parent1
__|__Child1-Child2-Parent1
Parent2
__Child1-Parent2
__Child2-Parent2
__|__Child1-Child2-Parent2
Parent3
Parent4
__Child-parent4

Create category table.

CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`description` text NOT NULL,
`image` varchar(250) NOT NULL,
`order` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0' COMMENT '0=> inactive, 1=>active',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Open models/Category.php. Then add below code,

public function getCategories($parent_id = 0, $exclude = '', $space = '', $categories='')
{
if($parent_id == 0){
$space = '';
$categories = array();
}else{
$space .='- ';
}

$model = Category::findAll([
'parent_id' => $parent_id,
]);
if(!empty($model)){
foreach ($model as $key) {
if($key->id == $exclude) continue;
$categories[] = array('id'=>$key->id, 'name'=>$space.$key->name);
$categories = $this->getCategories($key->id, $exclude, $space, $categories);
}
}

return $categories;
}

Open views/category/_form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Category;
?>

<?php 
 $category = new Category;
 $categories = $category->getCategories(0, $model->id);
 $items = ArrayHelper::map($categories, 'id', 'name');
?>
<?php echo $form->field($model, 'parent_id')->dropDownList($items,['prompt'=>'--None--']); ?>
'btn btn-success']) ?>
<?php ActiveForm::end(); ?> </div>

Woocommerce – Display shopping cart details on a WordPress menu

Open your theme’s functions.php.

Add below code:

add_filter('wp_nav_menu_items','wc_custom_menu_cart', 10, 2);
function wc_custom_menu_cart($menu, $args) {

 // Check if WooCommerce is active and add a new item to a menu assigned to Primary Navigation Menu location
 if ( !in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || 'primary' !== $args->theme_location )
 return $menu;

 $cart_url = WC()->cart->get_cart_url();
 $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 $viewing_cart = __('View your shopping cart', 'exploore');
 $start_shopping = __('Start shopping', 'exploore');
 $count = (int) WC()->cart->cart_contents_count;
 $cart_contents = sprintf(_n('%d item', '%d items', $count, 'exploore'), $count);
 $cart_total = WC()->cart->get_cart_total();
 
 $menu_item = '<li>';
 if ( $count > 0 ) { 
 $menu_item.= '<a class="cart-contents" href="'. $cart_url .'" title="'. $viewing_cart .'">';
 } else {
 $menu_item.= '<a class="cart-contents" href="'. $shop_page_url .'" title="'. $start_shopping .'">';
 }
 $menu_item.= '<i class="fa fa-shopping-cart"></i> ';
 $menu_item.= $cart_contents.' - '. $cart_total;
 $menu_item.= '</a>';
 $menu_item.= '</li>';

 $menu.=$menu_item;

 return $menu;
}

function my_header_add_to_cart_fragment( $fragments ) {
 
 ob_start();
 $cart_url = WC()->cart->get_cart_url();
 $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );
 $viewing_cart = __('View your shopping cart', 'exploore');
 $start_shopping = __('Start shopping', 'exploore');
 $count = WC()->cart->cart_contents_count;
 $cart_contents = sprintf(_n('%d item', '%d items', $count, 'exploore'), $count);
 $cart_total = WC()->cart->get_cart_total();

 if ( $count == 0 ) {
 ?>
 <a class="cart-contents" href="<?php echo $shop_page_url;?>" title="<?php echo $start_shopping;?>"><i class="fa fa-shopping-cart"></i> <?php echo $cart_contents.' - '. $cart_total;?></a>
 <?php } else { ?>
 <a class="cart-contents" href="<?php echo $cart_url;?>" title="<?php echo $viewing_cart;?>"><i class="fa fa-shopping-cart"></i> <?php echo $cart_contents.' - '. $cart_total;?></a>
 <?php
 }
 $fragments['a.cart-contents'] = ob_get_clean();
 
 return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );