Pages

Thursday, January 18, 2018

Thursday, November 5, 2015

Contact form 7 remoce select box (Dropdown) default value

function my_wpcf7_form_elements($html) {
function replace_include_blank($name, $text, &$html) {
$matches = false;
preg_match('/
if ($matches) {
$select = str_replace('', '', $matches[0]);
$html = preg_replace('/
}
}
replace_include_blank('mc4wp-age', 'AGE*', $html);
return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

Thursday, October 15, 2015

Get Vimeo video id from embaded code - PHP

function parse_vimeo($link){
        $regexstr = '~
            # Match Vimeo link and embed code
            (?:< iframe [^>]*src=")?       # If iframe match up to first quote of src
            (?:                         # Group vimeo url
                https?:\/\/             # Either http or https
                (?:[\w]+\.)*            # Optional subdomains
                vimeo\.com              # Match vimeo.com
                (?:[\/\w]*\/videos?)?   # Optional video sub directory this handles groups links also
                \/                      # Slash before Id
                ([0-9]+)                # $1: VIDEO_ID is numeric
                [^\s]*                  # Not a space
            )                           # End group
            "?                          # Match end quote if part of src
            (?:[^>]*></ iframe >)?        # Match the end of the iframe
            (?:.*
)?              # Match any title information stuff
            ~ix';
        preg_match($regexstr, $link, $matches);
        return $matches[1];
    }

Wednesday, October 14, 2015

Wordpress Activate plugin programatically

function run_activate_plugin( $plugin ) {
    $current = get_option( 'active_plugins' );
    $plugin = plugin_basename( trim( $plugin ) );

    if ( !in_array( $plugin, $current ) ) {
        $current[] = $plugin;
        sort( $current );
        do_action( 'activate_plugin', trim( $plugin ) );
        update_option( 'active_plugins', $current );
        do_action( 'activate_' . trim( $plugin ) );
        do_action( 'activated_plugin', trim( $plugin) );
    }

    return null;
}
run_activate_plugin( 'plugin_dir/plugin_file.php' );

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);
}
?>