Seach

simple list example

list_demo = list(['hithin','baby','chandran']) #list creation using constructor list
list_demo = ['hithin','baby','chandran'] #normal list creation
print(type(list_demo)) #used to check what type of data it is
print(list_demo) #print all data
print(list_demo[0])#prints 0th index data
print(list_demo[0:2])#prints 0th and 1st index data

simple dictionary nesting example

person={
   1:{
      "age":20,
      "gender":"645654"
   },2:{
      "age":30,
      "gender":"344445455"
   },3:{
      "age":60
   }
} creates a list name called person

for value in person:
    print(person.get(value).get("age"))
#get() used to get the value of the list based on key

metabox file upload wordpress code

<?php
function aw_include_script() {
    if ( ! did_action( 'wp_enqueue_media' ) ) {

        wp_enqueue_media();
    }
wp_enqueue_script( 'awscript', get_stylesheet_directory_uri() . '/js/awscript.js', array('jquery'), null, false );
}
add_action( 'admin_enqueue_scripts', 'aw_include_script' );

function aw_custom_meta_boxes( $post_type, $post ) {
    add_meta_box(

        'aw-meta-box',

        __( 'Custom Image' ),

        'render_aw_meta_box',

        array('slider'), //post types here

        'normal',

        'high'

    );
}

add_action( 'save_post', 'cd_meta_box_save' );

function cd_meta_box_save( $post_id )

{

    if(isset($_POST['aw_custom_image']))

    {

        $file =  $_POST['aw_custom_image'];

        update_post_meta($post_id,'file',$file);

    }

}

add_action( 'add_meta_boxes', 'aw_custom_meta_boxes', 10, 2 );

function render_aw_meta_box($post) {
    $image = get_post_meta($post->ID, 'file', true);
    ?>
    <table>
        <tr>
            <td><a href="#" class="aw_upload_image_button button button-secondary"><?php _e('Upload Image'); ?></a></td>
            <td><input type="text" name="aw_custom_image" id="aw_custom_image" value="<?php echo $image; ?>" /></td>
        </tr>
    </table>
    <script>
    jQuery(function($){

    $('body').on('click', '.aw_upload_image_button', function(e){
        e.preventDefault();
        var button = $(this),
        aw_uploader = wp.media({
            title: 'Custom image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        }).on('select', function() {
            var attachment = aw_uploader.state().get('selection').first().toJSON();
            $('#aw_custom_image').val(attachment.url);
        })
        .open();
    });

});</script>
    <?php
}

customizer example

 <?php

//https://maddisondesigns.com/2017/05/the-wordpress-customizer-a-developers-guide-part-1/

function diwp_theme_customize_options( $wp_customize)

{

    $wp_customize->add_panel( 'diwp_option_panel', array(

 

            'title' => 'Contact info',

            'priority' => 0,

            'capability' => 'edit_theme_options', 

            'theme_supports' => '',

            'active_callback' => ''

));

 

    

    $wp_customize->add_section( 'diwp_general_option_section', array(

 

            'title' => 'Contact options',

            'panel' => 'diwp_option_panel',

            'capability' => 'edit_theme_options',

            'theme_supports' => '',

            'active_callback' => '',

            'description_hidden' => false

 ));

    

    

    $wp_customize->add_setting( 'diwp_site_title', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));

    

    $wp_customize->add_control( 'diwp_site_title', array(

            'label'   => 'Phone Number',

            'description' => 'Add Phone Number',

            'section' => 'diwp_general_option_section',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'Enter Site Title' )

 )); 

    

    

    $wp_customize->add_setting( 'diwp_email', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));


    

    

    

    

    $wp_customize->add_control( 'diwp_email', array(

            'label'   => 'Email Addres',

            'description' => 'Add Email',

            'section' => 'diwp_general_option_section',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'Enter Site Title' )

 )); 

    

    

  $wp_customize->add_setting( 'diwp_working_hours', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));

    

    

    $wp_customize->add_control( 'diwp_working_hours', array(

            'label'   => 'Working hours',

            'description' => 'Add Working hours',

            'section' => 'diwp_general_option_section',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'Enter Site Title' )

 )); 

    

    $wp_customize->add_section( 'diwp_general_option_socialmedia', array(

 

            'title' => 'Social media contact',

            'panel' => 'diwp_option_panel',

            'capability' => 'edit_theme_options',

            'theme_supports' => '',

            'active_callback' => '',

            'description_hidden' => false

 ));

    

    $wp_customize->add_setting( 'facebook', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));


    $wp_customize->add_control( 'facebook', array(

            'label'   => 'Facebook',

            'description' => 'Add Facebook address',

            'section' => 'diwp_general_option_socialmedia',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'add facebook address' )

 )); 

    

     $wp_customize->add_setting( 'twitter', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));


    $wp_customize->add_control( 'twitter', array(

            'label'   => 'Twitter',

            'description' => 'Add twitter address',

            'section' => 'diwp_general_option_socialmedia',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'add twitter address' )

 )); 

    

    

     $wp_customize->add_setting( 'youtube', array(

 

            'default' => ' ',

            'type'      => 'theme_mod', 

            'transport' => 'refresh',  

            'theme_supports' => ''

 ));


    $wp_customize->add_control( 'youtube', array(

            'label'   => 'Twitter',

            'description' => 'Add youtube address',

            'section' => 'diwp_general_option_socialmedia',

            'type' => 'text',

            'input_attrs' => array( 'placeholder' => 'add youtube address' )

 )); 

    

    

    

    

    

    

    

}

add_action( 'customize_register', 'diwp_theme_customize_options' );

how to create a widget using code wordpress

 <?php

// Creating the widget 

class wpb_widget extends WP_Widget {

  

function __construct() {

parent::__construct(

  

// Base ID of your widget

'wpb_widget', 

  

// Widget name will appear in UI

__('WPBeginner Widget', 'wpb_widget_domain'), 

  

// Widget description

array( 'description' => __( 'Sample widget based on WPBeginner Tutorial', 'wpb_widget_domain' ), ) 

);

}

  

// Creating widget front-end

  

public function widget( $args, $instance ) {

$title = apply_filters( 'widget_title', $instance['title'] );

  

// before and after widget arguments are defined by themes

echo $args['before_widget'];

if ( ! empty( $title ) )

echo $args['before_title'] . $title . $args['after_title'];

echo $title;

?>

<input type="text" class="widefat"><input type="button" id="btn">

<script>

(function($)

{

$("#btn").bind('click',function(e)

{

alert();

});

}(jQuery));

</script>

<?php 

// This is where you run the code and display the output

echo __( 'Hello, World!', 'wpb_widget_domain' );

echo $args['after_widget'];

}

          

// Widget Backend 

public function form( $instance ) {

if ( isset( $instance[ 'title' ] ) ) {

$title = $instance[ 'title' ];

}

else {

$title = __( 'New title', 'wpb_widget_domain' );

}

// Widget admin form

?>

<p>

<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 

<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />

<textarea name="<?php echo $this->get_field_name( 'textarea' ); ?>" class="widefat">

<?php echo esc_attr( $instance['textarea']); ?>

</textarea>

</p>

<?php 

}

      

// Updating widget replacing old instances with new

public function update( $new_instance, $old_instance ) {

$instance = array();

$instance['textarea'] = $new_instance['textarea'];

$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

return $instance;

}

 

// Class wpb_widget ends here

 

 

// Register and load the widget

function wpb_load_widget() {

    register_widget( 'wpb_widget' );

}

add_action( 'widgets_init', 'wpb_load_widget' );

how to display contents in dashboard window in wordpress

this is a simple example to display user in the admin site

<?php
/*
Plugin name:dashboard
*/
function dashboard_widgets() {

wp_add_dashboard_widget(
                 'dashboard_widget',       
                 ' Dashboard Widget',       
                 'dashboard_widget_function'
        );
}
add_action( 'wp_dashboard_setup', 'dashboard_widgets' );
function dashboard_widget_function() {
$admin = get_admin_url()."user-edit.php?user_id=";
$users = get_users();
foreach($users as $key=>$item)
{
?>
<a target="_blank" href="<?php echo $admin.$item->data->ID; ?>"><?php echo $item->data->display_name;?></a><br/>
<?php
}
}

short code plugin in WordPress

<?php
/*
Plugin Name: shortcode
Plugin URI: https://hhiitthhiinn.blogspot.in
Version: 1.0
Author: Hithin
Author URI: https://hhiitthhiinn.blogspot.in
*/
function code($atts) {

$default = array
(
'type' => 'post',
'count' => -1,
'categoryid' => '',
'order' => 'ASC',
'taxonomy' => ''
);
    $attr = shortcode_atts($default,$atts);
$type = $attr['type'];
$count = $attr['count'];
$categoryid =$attr['categoryid'];
$taxonomy = $attr['taxonomy'];
$args = array(
'posts_per_page'   => $count,
'offset'           => 0,
'orderby'          => 'date',
'order'            => 'DESC',
'include'          => '',
'exclude'          => '',
'meta_key'         => '',
'meta_value'       => '',
'post_type'        => $type,
'post_mime_type'   => '',
'post_parent'      => '',
'author'    => '',
'author_name'    => '',
'post_status'      => 'publish',
'suppress_filters' => true,
'tax_query' => array(
        'taxonomy' => $taxonomy,
'field' => 'term_id',
        'terms' =>$categoryid
    )
);
$posts = get_posts( $args );
foreach($posts as $key=>$item)
{
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $item->ID ), 'thumbnail' );
$image = $image[0];
?>
<style>
.item {
    float: left;
    border: 1px double #ccc;
    margin: 5px !important;
}

</style>
<div  class="slick-slide item slick-cloned" data-slick-index="-3" aria-hidden="true" tabindex="-1" >
<figure class="slick-slide-inner">
<a target="_blank" href="<?php echo get_post_permalink($item->ID); ?>"><img class="slick-slide-image" src="<?php echo $image; ?>" alt="poster_5_up"></a>
</figure>

</div>
<?php
}
?>
<?php
}
add_shortcode('code', 'code');
?>
[code  parmeters (categoryid,taxonamy,count,order) ]

how to upgrade wordpress core and plugins

  • download new WordPress files and delete htaccess,wp-content,wp-config.php from it
  • the go to the old WordPress site remove all files and folders except wp-config.php,.htaccess,wp-content from it
  • the copy and past it
same in the case of the plugin 
backup plugin and update the news plugin check for any error or template broken in the site
then move to next plugin

reference



how to create a http post request using curl in php

<?php
$url ='http://localhost/curl/data.php'; //data to be dumped
$data = array
(
'name'=>"xxx",
'age'=>'xxx',
'gender'=>'xxxxx',
'phone'=>'xxxxxxxxxxx'
);
$curl = curl_init(); //curl initalizing
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL =>$url,
    CURLOPT_POST => 1, //setting it to post request
    CURLOPT_POSTFIELDS =>$data
));//option array
$resp = curl_exec($curl); //curl executed
$error = curl_error($curl); //getting error
if(!$error)
{
print_r($resp);
}
curl_close($curl); //closing the curl
?>

post curl file

how to configure and use a plugin cordova

or you can search the plugin in the 
<plugin name="cordova-plugin-contacts"            source="npm" spec="~2.0.1" />
Add this to your config.xml
document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        var myContact = navigator.contacts.create({"displayName": "Test User"});
        myContact.note = "This contact has a note.";
        console.log("The contact, " + myContact.displayName + ", note: " + myContact.note);
    }
This will create a contact test user in your mobile phone


remove index.php in codeignitor and routing

we need to add a small .htaccess script in the root folder of the codeignitor 

.htaccess

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

if you want to remove the codeignitor  contoller from the url the we need to go to applicatio folder then the config folder route.php here add $route['about']='Front/about';
here front is the controller and the about is the function name
htaccess remove the usage of index.php and route remove the full usage of front/about 
now we can access the page by about/inde page

create a custom theme settings in drupal7

create a file called theme--settings.php inside the theme folder in sites/all/theme we use the hook
theme_form_system_theme_settings_alter to add a settings for to default settings page

function hithin_form_system_theme_settings_alter(&$form, $form_state) 
 { 
$form["socialmedia"]=array (
 "#type"=>"fieldset", "#title"=>t("Socialmedia"), "#collapsible"=>TRUE, "#collapsed"=>TRUE ); 
}
read formapi for further details of the form

create a callback menu in drupal7

create a module 
function modulename_menu()
{
$items['link'] = array( 
    'title' => 'page title',
    'page callback' => 'callback ', 
    'access callback' => TRUE
  );
return $items;
}
function callback()
{
echo "hello";
}
clear the drupal cache then 
type url of the domain/link

create theme options in wordpress

add this to your functions.php
<?php
function create_theme_option()
{
$menu_slug=$page_title="themeoptions";
$menu_title="Theme Options";
    $capablity="manage_options";
    $callback="create_options";
   // $callback=plugins_url()."/themeoptions/home.php";
    $menuicon="dashicons-admin-generic";
    $position=50;
    add_menu_page($page_title,$menu_title,$capablity,$menu_slug,$callback,$menuicon,$position);
}
add_action("admin_menu","create_theme_option");
function create_options()
{
?>
<style type="text/css">
.theme-options input[type=text]
{
height:50px;
font-size:20px;
}
</style>
<h1>Theme options</h1>
<form method="post" action="options.php" class="theme-options" >
<?php
           settings_fields("Socialmedia");
           do_settings_sections("theme-options");  
settings_fields("footer");
           submit_button();
       ?>    
</form>
<?php
}
function footer()
{?>
<input type="text" name="footer" id="footer" class="widefat" value="<?php  echo get_option('facebook'); ?>" >
<?php }
function facebook()
{?>
<input type="text" class="widefat" id="facebook" value="<?php  echo get_option('facebook'); ?>" name="facebook"  >
<?php
}
function linkedin()
{?>
<input type="text" class="widefat" id="linkedin" value="<?php  echo get_option('linkedin'); ?>" name="linkedin"   >

<?php }

function settings()
{
add_settings_section("Socialmedia", "Social Media", null, "theme-options");
add_settings_section("footer", "Footer", null, "theme-options");

add_settings_field("facebook", "Facebook Link", "facebook", "theme-options", "Socialmedia");
register_setting("Socialmedia", "facebook");
add_settings_field("linkedin", "Linkedin Link", "linkedin", "theme-options", "Socialmedia");
register_setting("Socialmedia", "linkedin");
add_settings_field("footer", "Footer Text", "footer", "theme-options", "footer");
register_setting("Socialmedia", "footer");
}
add_action("admin_init", "settings");

create a widget area in your current theme

add this to your functions.php

<?php
function widget_init()
{
    register_sidebar( array(
'name'          => esc_html__( 'Footer Widget Area 1', 'shopbiz-child' ),
'id'            => 'footer_widget_area-1',
'description'   => '',
'before_widget' => '<div id="%1$s" class="col-md-3 col-sm-6 rotateInDownLeft animated ta-widget %2$s">',
'after_widget'  => '</div>',
'before_title'  => '<h6>',
'after_title'   => '</h6>',
) );
}
add_action('widgets_init','widget_init');

create a custom widget in wordpress

in order to create a custom widget we need to extend the Wp_widget class in wordpress and we use 3 methods for creating and widget form,widget,update.form is backend ui of the widget and widget is used to display to frontend and update is used to update the widget field values.Two approaches can be used to create widget
1:creating widget as plugin
2:add code to functions.php
Here i created widget as plugin
basic skelton

class wiget_name extends Wp_widget
{
function widget()
{
parent::WP_Widget(false, $name = __('widget name', 'wp_widget_plugin') );
}
public function update($new,$old)
{
//updates the widget field
}
public function form($instance)
{
//ui creation
}
public function widget($arg,$instance)
{
//front end display
}
}


Click here to download sample working code

dynamic javascript loader

this script aim is to load js files dynamically by passing the location as an array and dynamically include it to dom
load.html
<html>
<head>
<script type="text/javascript" src="load.js" >

</script>
</head>
<body>
<script type="text/javascript" >
options=["module","module1"];//scripts to be loaded
obj.create(options);//calling the creater function
</script>
</body>
</html>
load.js(created using modular design pattern)
var obj=(function()
{

var obj=
{};
this.create=function(script)
{
//script is an array containing the names of the scripts need to be included
for(i=0;i<script.length;i++)
{
js=script[i]+".js";
element=document.createElement('script');//creating dom element script
element.setAttribute('type','text/javascript');//setting script attributes
    element.setAttribute('src',js);
    document.getElementsByTagName('head')[0].appendChild(element);//appending it to head
  }
 
}
return this;

}());

modular javascript approach and event binding

simple adding application using modular javascript and html
<html>
<body>
<input type="text" id="t1">
<input type="text" id="t2">
<input type="button" id="b1" value="Add">
<script type="text/javascript" src="module1.js">

</script>
</body>

</html>
script file
"use strict";
var obj=(function()
{
obj={};
obj.add=function()
{
var n1=parseInt(document.getElementById("t1").value);
var n2=parseInt(document.getElementById("t2").value);
var sum=n1+n2;
alert(sum);
};
return obj;
}());

//document.getElementById("b1").addEventlistner("click",obj.add);
document.getElementById("b1").onclick=obj.add;

custom jquery image slider plugin

create a js and insert this code
(function($)
{
$.slideshow=function(selector,options)
{
    var settings=
    {
    "delay":2000,
    "fadespeed":500,
    };
    $.extend(settings,options);
    var obj = $(selector);
        var img = obj.children('img');
        var count = img.length;
    img.eq(0).show();
 
    i=0;
    setInterval(function()
       {
       img.eq(i).fadeOut(settings.delay);
       i = (i+1==count) ? 0:i=i+1;
       img.eq(i).fadeIn(settings.fadespeed);
       },2000);
     
};
}(jQuery));


create a Html file and insert this
<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="bootstrap/js/jquery.js"></script>
        <script src="js/slideshow.js"></script>
        <link rel="stylesheet" href="css/slidshow.css">
    </head>
    <body>
        <section class="slider">
            <img src="image/1.jpg">
            <img src="image/2.jpg">
            <img src="image/3.jpg">
            <img src="image/4.jpg">
        </section>
        <script>
            (function($)
            {
               $(document).ready(function(e)
               {
                   options=
                   {
                    "delay":2000,
                    "fadespeed":600,          
                   };
                   $.slideshow(".slider",options);
               });
             
            }(jQuery));
        </script>
    </body>
</html>


php ajax wordpress example

wp_ajax_function_name,wp_ajax_nopri_function_name are the methods used for secure ajax call in wordpress to admin-ajax.php here is a simple example for ajax wordpress call .for privilage user we user wp_ajax_function name,for non privilage user we use wp_ajax_nopri_function_name here is an example for it
create a plugin and add ajax.php
<?php
/*
 * Plugin Name:ajax
 */
function my_ajax_callback_function() {
        echo "hiii";
        exit();
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );  
// If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );

create a js file and add it to wordpress 
(function($)
    {
        $(document).ready(function(e)
        {
           $.ajax(
                   {
                       url: "<?php echo admin_url('admin-ajax.php'); ?>",
                       type: 'POST',
                       data: 
                               ({action  : "my_action_name","name":"xxx","age":"xxx"}),
                       success: function (data, textStatus, jqXHR) {
                        console.log(data);
                    }
                   });
        });
    }(jQuery));
by using a plugin we dont need to inser directly into the functions.php of the wordpress