Pages

Wednesday, October 15, 2014

PHP unzip file code

$oldPath =  $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
$path = str_replace("unzip.php","",$oldPath);
echo $path;

$zip = new ZipArchive;
$res = $zip->open('dadinfo.zip');
if ($res === TRUE) {
  $zip->extractTo($path);
  $zip->close();
  echo 'woot!';
} else {
  echo 'doh!';
}
?>

Tuesday, August 26, 2014

Remove Comments Section from wordpress.

a) Redirect any user trying to access comments page
function disable_comments_admin_menu_redirect() {
global $pagenow;
if ($pagenow === 'edit-comments.php') {
wp_redirect(admin_url()); exit;
}
}
add_action('admin_init', 'disable_comments_admin_menu_redirect');

b) Close comments on the front-end
function disable_comments_status() {
return false;
}
add_filter('comments_open', 'disable_comments_status', 20, 2);
add_filter('pings_open', 'disable_comments_status', 20, 2);

c) Hide existing comments
function disable_comments_hide_existing_comments($comments) {
$comments = array();
return $comments;
}
add_filter('comments_array', 'disable_comments_hide_existing_comments', 10, 2);

d) Disable support for comments and trackbacks in post types
function disable_comments_post_types_support() {
$post_types = get_post_types();
foreach ($post_types as $post_type) {
if(post_type_supports($post_type, 'comments')) {
remove_post_type_support($post_type, 'comments');
remove_post_type_support($post_type, 'trackbacks');
}
}
}
add_action('admin_init', 'disable_comments_post_types_support');

e) Remove comments page in menu
function disable_comments_admin_menu() {
remove_menu_page('edit-comments.php');
}
add_action('admin_menu', 'disable_comments_admin_menu');

f) Remove comments links from admin bar
function disable_comments_admin_bar() {
if (is_admin_bar_showing()) {
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
}
}
add_action('init', 'disable_comments_admin_bar');

g) Remove comments metabox from dashboard
function disable_comments_dashboard() {
remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
}
add_action('admin_init', 'disable_comments_dashboard');

Thursday, July 10, 2014

WordPress Social Login Redirect - [Solved]

add_filter('wsl_process_login_get_redirect_to','wp_social_plugin_custom_redirect');
function wp_social_plugin_custom_redirect() {
return get_permalink(2);
}

add_filter('login_redirect','bpdev_redirect_to_profile',100,3);
function wp_custom_redirect( $redirect_to, $request, $user ) {
global $user;
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
if ( in_array( 'administrator', $user->roles ) ) {
// redirect them to the default place
return $redirect_to;
} else {
return get_permalink();
}
} else {
return $redirect_to;
}
}

Tuesday, June 10, 2014

Wordpress add user meta fields - [resolved]


function wp_vendor_products_upload_limit( $user ) {
if ( is_super_admin() ) {
?>
<h3><?php _e('Vendor Product Upload Limit'); ?></h3>

<table class="form-table">
<tr>
<th>
<label for="no_of_vendor_products"><?php _e('No of Products'); ?>
</label></th>
<td>
<input type="text" name="no_of_vendor_products" id="no_of_vendor_products" value="<?php echo esc_attr( get_the_author_meta( 'no_of_vendor_products', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description"><?php _e('Please enter no. of products.'); ?></span>
</td>
</tr>
</table>
<?php
}
}

function wp_save_vendor_products_upload_limit( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) )
return FALSE;

update_usermeta( $user_id, 'no_of_vendor_products', $_POST['no_of_vendor_products'] );
}

add_action( 'show_user_profile', 'wp_vendor_products_upload_limit' );
add_action( 'edit_user_profile', 'wp_vendor_products_upload_limit' );

add_action( 'personal_options_update', 'wp_save_vendor_products_upload_limit' );
add_action( 'edit_user_profile_update', 'wp_save_vendor_products_upload_limit' );


add_action('manage_users_columns','remove_user_posts_column');
function remove_user_posts_column($column_headers) {
    unset($column_headers['posts']);
    return $column_headers;
}

How to display wordpress posts view count? - [Solved]

1. Please write below code in functions.php

<?php
// function to display number of views for post
function wp_get_post_views($postId){
    $count_key = 'count_post_views';
    $count = get_post_meta($postId, $count_key, true);
    if($count == ''){
        delete_post_meta($postId, $count_key);
        add_post_meta($postId, $count_key, '0');
        return '0 View';
    }
    return $count.' Views';
}

// function to set post views
function wp_set_post_views($postId) {
    $count_key = 'count_post_views';
    $count = get_post_meta($postId, $count_key, true);
    if($count == ''){
        $count = 0;
        delete_post_meta($postId, $count_key);
        add_post_meta($postId, $count_key, '0');
    }
else
{
        $count++;
        update_post_meta($postId, $count_key, $count);
    }
}

// add views column to wp_admin
add_filter('manage_posts_columns', 'wp_posts_views_column');
function wp_posts_views_column($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}

add_action('manage_posts_custom_column', 'wp_posts_views_custom_column',10,2);
function wp_posts_views_custom_column($column_name, $id){
    if($column_name === 'post_views'){
        echo wp_get_post_views(get_the_ID());
    }
}
?>

2. Now, open singe.php and add below code inside the loop.


<?php
wp_set_post_views(get_the_ID());
?>

3. Please write below code for display views of post.

<?php
wp_get_post_views(get_the_ID());
?>


4. If you want to sort post by view than add below code:

<?php
$args = array(  'numberposts'  => 10,
                'orderby'      => 'meta_value',
                'meta_key'     => 'count_post_views',
                'order'        => 'DESC',
                'post_type'    => 'post',
                'post_status'  => 'publish'
            );
$mostViewedPosts = get_posts( $args );
foreach( $mostViewedPosts as $mostViewedPost ) {
/* Write your code here */
}
?>

Monday, June 9, 2014

Woocommerce create role for vendor and add products capabilities for him

Please write below code in functions.php



add_role('shop_vendor', 'Shop Vendor', array(
'read' => true,
'read_product' => true,
'edit_product' => true,
'edit_products' => true,
'edit_private_products' => true,
'delete_product' => true,
'delete_products' => true,
'delete_published_products' => true,
'publish_product' => true,
'publish_products' => true,
'edit_published_products' => true,
'assign_product_terms' => true,
));

Monday, June 2, 2014

WP_List_Table




$testData = new Test_List_Table();
$testData->prepare_items();
?>



$testData->search_box( 'search', 'search_id' );
$testData->display(); 
?>
 

if( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

class Test_List_Table extends WP_List_Table
{
/**
     * Prepare the items for the table to process
     *
     * @return Void
     */
    public function prepare_items()
    {
        $columns = $this->get_columns();
        $hidden = $this->get_hidden_columns();
        $sortable = $this->get_sortable_columns();

        $data = $this->table_data();
        usort( $data, array( &$this, 'sort_data' ) );

        $perPage = 10;
        $currentPage = $this->get_pagenum();
        $totalItems = count($data);

        $this->set_pagination_args( array(
            'total_items' => $totalItems,
            'per_page'    => $perPage
        ) );

        $data = array_slice($data,(($currentPage-1)*$perPage),$perPage);

        $this->_column_headers = array($columns, $hidden, $sortable);
$this->process_bulk_action();
        $this->items = $data;
    }

    /**
     * Override the parent columns method. Defines the columns to use in your listing table
     *
     * @return Array
     */
    public function get_columns()
    {
$columns = array(
'cb'        => '',
'title' => 'Title',
'sort_desc' => 'Short Description',
'edit' => 'Edit',
'view' => 'View',
'delete' => 'Delete'
);

        return $columns;
    }

    /**
     * Define which columns are hidden
     *
     * @return Array
     */
    public function get_hidden_columns()
    {
        return array();
    }

    /**
     * Define the sortable columns
     *
     * @return Array
     */
    public function get_sortable_columns()
    {
        return array('title' => array('title', false));
    }

function get_bulk_actions() {
$actions = array(
'delete_multi'    => 'Delete'
);
return $actions;
}

function column_cb($item) {
        return sprintf(
            '', $item['id']
        );    
    }

    /**
     * Get the table data
     *
     * @return Array
     */
    private function table_data()
    {
        $data = array();
global $wpdb;

$whereCnd = '';
if(isset($_REQUEST['s'])){
$whereCnd = ' Search query ' ;
}

$listsData = $wpdb->get_results( "Main Query");

if(!empty($listsData)) {

foreach($listsData as $key => $val){
$delNonce = wp_create_nonce( 'wp-list-'.$val->ID.'-delete-nonce' );
$data[] = array(
'id'        => $val->ID,
'title' => $val->title,
'sort_desc' => $val->sort_description,
'edit' => 'edit',
'view' => 'View',
'delete' => 'Delete'
);
}

        return $data;
    }

    /**
     * Define what data to show on each column of the table
     *
     * @param  Array $item        Data
     * @param  String $column_name - Current column name
     *
     * @return Mixed
     */
    public function column_default( $item, $column_name )
    {
        switch( $column_name ) {
            case 'id':
            case 'title':
            case 'sort_desc':
            case 'edit':
            case 'view':
            case 'delete':
return $item[ $column_name ];
            default:
                return print_r( $item, true ) ;
        }
    }

    /**
     * Allows you to sort the data by the variables set in the $_GET
     *
     * @return Mixed
     */
    private function sort_data( $a, $b )
    {
        // Set defaults
        $orderby = 'title';
        $order = 'asc';

        // If orderby is set, use this as the sort column
        if(!empty($_GET['orderby']))
        {
            $orderby = $_GET['orderby'];
        }

        // If order is set use this as the order
        if(!empty($_GET['order']))
        {
            $order = $_GET['order'];
        }


        $result = strcmp( $a[$orderby], $b[$orderby] );

        if($order === 'asc')
        {
            return $result;
        }

        return -$result;
    }

function process_bulk_action() {        
global $wpdb;
        if( 'delete_multi'===$this->current_action() ) {
global $wpdb;

if(is_array($_REQUEST['id'])) 
{
echo "Your actions";
}
die();
        }        
    }

}

Sunday, May 18, 2014

Check XSS script when form submit - PHP

If you want to check XSS script than please write below code:

checkMagicQuotes();
checkXssScript();

function checkMagicQuotes()
{
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
function stripslashes_deep($value)
   {
       return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
   }
   $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
}

function checkXssScript()
{
function stripXss($value)
{
$tags = array(
    '@<script[^>]*?>.*?</script>@si',
    '@&#(\d+);@e',
    '@\[\[(.*?)\]\]@si',
    '@\[!(.*?)!\]@si',
    '@\[\~(.*?)\~\]@si',
    '@\[\((.*?)\)\]@si',
    '@{{(.*?)}}@si',
    '@\[\*(.*?)\*\]@si'
   );
   return is_array($value) ? array_map('stripXss', $value) : preg_replace($tags, '', $value);
}
$_POST    = array_map('stripXss', $_POST);
$_GET     = array_map('stripXss', $_GET);
$_COOKIE  = array_map('stripXss', $_COOKIE);
$_REQUEST = array_map('stripXss', $_REQUEST);
}

Monday, May 12, 2014

convert PHP Array to XML with attributes - [resolved]

If you want to convert array to XML in PHP than please use below class:

$xml = Array2XML::createXML('OrderLists', $orderXML);

class Array2XML {

    private static $xml = null;
private static $encoding = 'UTF-8';

    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DomDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
self::$encoding = $encoding;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DomDocument
     */
    public static function &createXML($node_name, $arr=array()) {
        $xml = self::getXMLRoot();
        $xml->appendChild(self::convert($node_name, $arr));

        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $xml;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMNode
     */
    private static function &convert($node_name, $arr=array()) {

        //print_arr($node_name);
        $xml = self::getXMLRoot();
        $node = $xml->createElement($node_name);

        if(is_array($arr)){
            // get the attributes first.;
            if(isset($arr['@attributes'])) {
                foreach($arr['@attributes'] as $key => $value) {
                    if(!self::isValidTagName($key)) {
                        throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                    }
                    $node->setAttribute($key, self::bool2str($value));
                }
                unset($arr['@attributes']); //remove the key from the array once done.
            }

            // check if it has a value stored in @value, if yes store the value and return
            // else check if its directly stored as string
            if(isset($arr['@value'])) {
                $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
                unset($arr['@value']);    //remove the key from the array once done.
                //return from recursion, as a note with value cannot have child nodes.
                return $node;
            } else if(isset($arr['@cdata'])) {
                $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
                unset($arr['@cdata']);    //remove the key from the array once done.
                //return from recursion, as a note with cdata cannot have child nodes.
                return $node;
            }
        }

        //create subnodes using recursion
        if(is_array($arr)){
            // recurse to get the node for that key
            foreach($arr as $key=>$value){
                if(!self::isValidTagName($key)) {
                    throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
                }
                if(is_array($value) && is_numeric(key($value))) {
                    // MORE THAN ONE NODE OF ITS KIND;
                    // if the new array is numeric index, means it is array of nodes of the same kind
                    // it should follow the parent key name
                    foreach($value as $k=>$v){
                        $node->appendChild(self::convert($key, $v));
                    }
                } else {
                    // ONLY ONE NODE OF ITS KIND
                    $node->appendChild(self::convert($key, $value));
                }
                unset($arr[$key]); //remove the key from the array once done.
            }
        }

        // after we are done with all the keys in the array (if it is one)
        // we check if it has any text value, if yes, append it.
        if(!is_array($arr)) {
            $node->appendChild($xml->createTextNode(self::bool2str($arr)));
        }

        return $node;
    }

    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }

    /*
     * Get string representation of boolean value
     */
    private static function bool2str($v){
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }

    /*
     * Check if the tag name or attribute name contains illegal characters
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn
     */
    private static function isValidTagName($tag){
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
    }
}


Source From: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/

Mapping multiple domains to wordpress

If you want to mapping multiple domains to one blog than you have to follow below procedure:

1. Point all domains nameserver(DNS) from domain account settings.
2. Than write below code in "wp-config.php" file after "table_prefix" code:

- define('WP_SITEURL','http://'.$_SERVER['HTTP_HOST']);
- define('WP_HOME','http://'.$_SERVER['HTTP_HOST']);

- Now, go to the wordpress admin panel >> General >> Settings. Here, you can see "WordPress Address (URL)" and "Site Address (URL)" both are disabled. It means your wordpress is ready for multiple domains.

Thursday, May 8, 2014

MySQL Update Query using a join

If you want to update any records with join of two tables than please write below code:

Update wp_posts as p
LEFT JOIN wp_postmeta as pm on pm.post_id = p.ID
set p.post_title = "changed title" where pm.meta_key = 'test_post_meta' AND pm.meta_value = '123345346'

Tuesday, May 6, 2014

jQuery multiple radio fields validation of groups

- I have below options for input radio fields:

<input type="radio"  name="option1" value="1" />
<input type="radio"  name="option1" value="2" />
<input type="radio"  name="option1" value="3" />
<input type="radio"  name="option1" value="4" />
                                           
<input type="radio"  name="option2" value="5" />
<input type="radio"  name="option2" value="6" />
<input type="radio"  name="option2" value="7" />
<input type="radio"  name="option2" value="8" />

<input type="radio"  name="option3" value="9"  />
<input type="radio"  name="option3" value="10" />
<input type="radio"  name="option3" value="11" />
<input type="radio"  name="option3" value="12" />

<input type="radio"  name="option4" value="13" />
<input type="radio"  name="option4" value="14" />
<input type="radio"  name="option4" value="15" />
<input type="radio"  name="option4" value="16" />


- Please write below jQuery for all radio fields:

var radioNames = []
    $('input[type="radio"]').each(function () {
        var radioName = $(this).attr('name');
        if ($.inArray(radioName, radioNames) == -1) radioNames.push(radioName);
    });

    // validation for each radio group
    $.each(radioNames, function (i, fieldName) {
        if ($('input[name="' + fieldName + '"]:checked').length == 0) {
            console.log('Please check ' + fieldName);
        }
    });

Creating "Hello World" Magento Module

To start with a new Magento module, you have to create a module code folder under an appropriate code pool.
Lets create "Hello World" module module.

Step 1:

- Please create ".xml" file for module as below:
\app\etc\modules\Demomodule_Helloworld.xml

<?xml version="1.0"?>
<config>
<modules>
<Demomodule_Helloworld>
<active>true</active>
<codePool>local</codePool>
</Demomodule_Helloworld>
</modules>
</config>


Step 2:

Now, you have to create config file for module setup as below:

\app\code\local\Demomodule\Helloworld\etc\config.xml

<?xml version="1.0"?>
<config>
<modules>
<Demomodule_Helloworld>
<version>1.0.0</version>
</Demomodule_Helloworld>
</modules>
<frontend>
        <routers>
            <helloworld>
                <use>standard</use>
                <args>
                    <module>Demomodule_Helloworld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
        <layout>
            <updates>
                <helloworld>
                    <file>helloworld.xml</file>
                </helloworld>
            </updates>
        </layout>
    </frontend>
</config>


Step 3: 

Please create controller file with below information.

\app\code\local\Demomodule\Helloworld\controllers\IndexController.php

<?php
class Demomodule_Helloworld_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
$this->loadLayout();     
$this->renderLayout();
    }
}

Step 4:

Please create ".xml" file for plugin "Block" setup as below:

\app\design\frontend\default\default\layout\helloworld.xml

<?xml version="1.0"?>
    <layout version="0.1.0">
<helloworld_index_index>
<reference name="content">
<block type="core/template" name="helloworldpage" template="helloworld/content.phtml"/>
</reference>
</helloworld_index_index>

</layout>


Step 5:

Now, you have to create new ".phtml" file for your content as below:

\app\design\frontend\default\default\template\helloworld\content.phtml

<div class="banner-left box">
<?php echo $this->__('This is the demo "Hello World" module.');?>
</div>

Thursday, May 1, 2014

Contact Form 7 Create Custom validation for all fields - [resolved]

If you want to add custom validation for contact form 7 input fields than please write below code:

add_filter('wpcf7_validate_FIELDNAME','cf7_custom_form_validation', 10, 2); // wpcf7_validate_email or wpcf7_validate_email*

function cf7_custom_form_validation($result,$tag) {
    /*
        Here you can write your custom code for validation
    */
}

Contact Form 7 customize response message - [resolved]

If you want to change response message by code for contact form 7 than please write below code:

add_action("wpcf7_ajax_json_echo", "cf7_change_response_message",10,2);

function cf7_change_response_message($items, $result){
    /*
        Here you can write your custom code for response message
    */
}

Monday, April 28, 2014

Wordpress pass variable when calling template - [resolved]

If you want to pass any variable when include template than please follow below method:

1. I want to send page ID to sidebar than I have create one array for this and pass it using below method:

<?php
$params = array(
'ID' => $parentId
);
getTemplatePart('sidebar', 'subpages', $params);
?>

2. If you want to get this array than please see at below code:

<?php
$parentId = $ID;

// here, you can set your login
?>

3. Please write below function in your functions.php for calling the template:

<?php
function getTemplatePart($slug = null, $name = null, array $params = array()) {
    global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;

    do_action("get_template_part_{$slug}", $slug, $name);
    $templates = array();
    if (isset($name))
        $templates[] = "{$slug}-{$name}.php";

    $templates[] = "{$slug}.php";

    $_template_file = locate_template($templates, false, false);

    if (is_array($wp_query->query_vars)) {
        extract($wp_query->query_vars, EXTR_SKIP);
    }
    extract($params, EXTR_SKIP);

    require($_template_file);
}
?>

Remove Extra "P" tags from content area in wordpress- [resolved]

If you want to remove extra "<p>" tags from content than please write below code in your functions.php

Method 1:

function wp_remove_extra_p_tags($content) {
    $array = array (
        '<p>[' => '[',
        ']</p>' => ']',
    );
    $content = strtr($content, $array);
return $content;
}
add_filter('the_content', 'wp_remove_extra_p_tags', 10);


Method 2:

function wp_remove_extra_p_tags($content) {
    $content = str_replace(array("<p></p>","<p> </p>"),"",$content);
    return $content;
}
add_filter('the_content', 'wp_remove_extra_p_tags');

Monday, April 14, 2014

Woocommerce change error message OR repalce default message - [resolved]

If you want to change default messages in woocommerce than you have to write below code in functions.php

function sagepay_woocommerce_add_error( $error ) {
    if( 'SagePay Direct - Card number required.' == $error ) {
        $error = 'Card number required.';
    } else if( 'SagePay Direct - Fullname required.' == $error ) {
        $error = 'Fullname required.';
    } else if( 'SagePay Direct - CV2 required.' == $error ) {
        $error = 'CV2 required.';
    }
    return $error;
}
add_filter( 'woocommerce_add_error', 'sagepay_woocommerce_add_error' );

Woocommerce Change/Remove Payment Gateway Icon-[resolved]

If anyone wants to change payment gateway details than he can do this from below way.
Please write "woocommerce_available_payment_gateways" hook in functions.php

function remove_sagepage_payment_gateway_icon( $gateways ) {
if(isset($gateways['sagepaydirect'])){
$gateways['sagepaydirect']->icon = '';
}
return $gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'remove_sagepage_payment_gateway_icon' );

Thursday, April 3, 2014

Woocommerce get top level category - [resolved]

function get_top_level_product_cat(){
    global $post;
    $prod_terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ($prod_terms as $prod_term) {

        // gets product cat id
        $product_cat_id = $prod_term->term_id;

        // gets an array of all parent category levels
        $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' ); 
       
        // This cuts the array and extracts the last set in the array
        $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
        foreach($last_parent_cat as $last_parent_cat_value){
            return $product_category = get_product_category_by_id( $last_parent_cat_value );           
        }
    }
}

function get_product_category_by_id( $category_id ) {
    $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
    return $term['name'];
}

Split to max characters without breaking word - PHP [resolved]

<?php

function split_str($str, $maxlen) {
    if (strlen($str) <= $maxlen) {
       return $str;
    } 
    $newstr = substr($str, 0, $maxlen);
    if ( substr($newstr,-1,1) != ' ' )
        $newstr = substr($newstr, 0, strrpos($newstr, " "));
    return $newstr;
}

echo split_str("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.", 22);

?>

Wednesday, March 26, 2014

file_get_contents not working with utf8 - [resolved]

If you want to encode special characters from "file_get_contents" than please write below code:

$stringCnt = file_get_contents("URL");
$stringCnt = mb_convert_encoding($stringCnt, 'UTF-8', mb_detect_encoding($stringCnt, 'UTF-8, ISO-8859-1', true));

You can encode "¡ÅѺ˹éÒáá¾ÃФÑÁÀÕÃìÀÒÉÒä·Â©ºÑº" characters.

And If you are using other language than you have to use other encoding method.

Tuesday, March 25, 2014

Highlight search tag on search result page - wordpress[resolved]


You can write below code in your search page:

$title = get_the_title(); 
$keys= explode(" ",$s); 
$title = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="red-bg">\0</span>', $title); 

$excerpt = get_the_excerpt();
$keys = explode(" ",$s);
$excerpt = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="red-bg">\0</span>', $excerpt);



<h2><?php echo $title; ?></h2>
<p><?php echo $excerpt;?></p>

How to set a default taxonomy for custom post types?

Please write below code in functions.php :

add_action( 'save_post', 'set_default_category' );
function set_default_category( $post_id ) {
    // Get the terms
    $terms = wp_get_post_terms( $post_id, 'your_custom_taxonomy');
    // Only set default if no terms are set yet
    if (!$terms) {
        // Assign the default category
        $default_term = get_term_by('name', 'taxonomy_slug', 'your_custom_taxonomy');
        $taxonomy = 'your_custom_taxonomy';
        wp_set_post_terms( $post_id, $default_term->term_id, $taxonomy );
    }
}

Tuesday, March 18, 2014

Redirect when "Error establishing a database connection" - Wordpress

If you want to redirect your website when you got "Error establishing a database connection" than please follow below way:

1. Create one page in "wp-content" directory with "db-error.php" name.
2. Now write your redirection code to this file.

Monday, February 3, 2014

How to disable the phpMyAdmin login page? - [solved]

Please open "config.inc.php" file which one is located in "\wamp\apps\phpmyadmin\"  directory.

After that add/update below lines:


$cfg['Servers'][$i]['auth_type'] = 'config'; //change authentication type "cookies" to "config"
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
$cfg['Servers'][$i]['AllowRoot'] = TRUE;

Thursday, January 30, 2014

How to change month format from archive widget? - [Resolved]


Please write below code in functions.php

add_filter('get_archives_link', 'translate_archive_month');

function translate_archive_month($list) {

     $patterns = array('/January/', '/February/', '/March/', '/April/', '/May/', '/June/', '/July/', '/August/', '/September/', '/October/',  '/November/', '/December/');

    $replacements = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');    

    $list = preg_replace($patterns, $replacements, $list);

    return $list; 

}

Friday, January 24, 2014

Repeater not saving on some pages, but works on others - [Solved]

If your ACF repeater fields are not updating after saving the post than please insert below code in ".htaccess" file. Which one is placed on your root directory.

php_value max_input_vars 10000
php_value memory_limit 500M
php_value max_execution_time 60
php_value post_max_size 500M

Monday, January 20, 2014

Remove default category slug from permalink - wordpress

Please write below code in functions.php

// Remove category base
add_action('init', 'no_category_base_permastruct');
function no_category_base_permastruct() {
global $wp_rewrite, $wp_version;
if (version_compare($wp_version, '3.4', '<')) {
$wp_rewrite -> extra_permastructs['category'][0] = '%category%';
} else {
$wp_rewrite -> extra_permastructs['category']['struct'] = '%category%';
}
}

// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_base_rewrite_rules');
function no_category_base_rewrite_rules($category_rewrite) {

$category_rewrite = array();
$categories = get_categories(array('hide_empty' => false));
foreach ($categories as $category) {
$category_nicename = $category -> slug;
if ($category -> parent == $category -> cat_ID)// recursive recursion
$category -> parent = 0;
elseif ($category -> parent != 0)
$category_nicename = get_category_parents($category -> parent, false, '/', true) . $category_nicename;

$category_rewrite['(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$category_rewrite['(' . $category_nicename . ')/?$'] = 'index.php?category_name=$matches[1]';
}
// Redirect support from Old Category Base
global $wp_rewrite;
$old_category_base = get_option('category_base') ? get_option('category_base') : 'category';
$old_category_base = trim($old_category_base, '/');
$category_rewrite[$old_category_base . '/(.*)$'] = 'index.php?category_redirect=$matches[1]';

return $category_rewrite;
}

Thursday, January 9, 2014

Add or update user column in admin panel - wordpress

add_filter('manage_users_columns', 'drop_video_columns_head');
function drop_video_columns_head($defaults_columns) {
unset($defaults_columns['posts']);
unset($defaults_columns['name']);
$defaults_columns['uservideos']  = 'Videos';
return $defaults_columns;
}
add_filter('manage_users_custom_column', 'drop_video_columns_content_users', 10, 3);
function drop_video_columns_content_users($c, $column_name, $user_id){

if ($column_name == 'uservideos') {
global $wpdb;
        $num_videos = $wpdb->get_results("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'youtube' AND post_status = 'publish' and post_author = {$user_id} ",'ARRAY_A');
return $num_videos[0]['COUNT(*)'];
}
}

Monday, January 6, 2014

How to Disable the WordPress Update Notice?

If you want to disable update notification in wordpress than please write below code in functions.php

/*******************  Method 1  ***********************/
//Disable Theme Updates # 3.0+
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_themes' );

//Disable Plugin Updates #3.0+
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_plugins' );

//Diasable Core Updates # 3.0+
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_version_check' );


/*******************  Method 2  ***********************/

function remove_core_updates(){

        global $wp_version;
        return (object) array(
            'last_checked' => time(),
            'version_checked' => $wp_version,
            );
}
add_filter('pre_site_transient_update_core', 'remove_core_updates');
add_filter('pre_site_transient_update_plugins', 'remove_core_updates');
add_filter('pre_site_transient_update_themes', 'remove_core_updates');

Friday, January 3, 2014

Get Page Id from Page Slug - Wordpress

If you want to get page id from page URL than you can use below function:

$postid = url_to_postid( $url );