vikas
Vikas Pandey@vikas

I am the best

  • 5 years-11 months

    how to add custom menu code in wordpress templates

    • Category : wordpress
    • Location : Chandigarh, India
    • Posted On : Feb 20, 2018
    • Posted by : Vikas

    If you want to add custom navigation menus in your WordPress templates? By default, many WordPress themes come with pre-defined menu locations and layouts. follow this article:

    <?php $defaults = array(
        'menu'            => 'main',
        'container'       => 'div',
        'container_class' => 'navbar-collapse collapse',
        'container_id' => 'navbar',
        'menu_class'      => 'nav navbar-nav navbar-right',
        'echo'            => true,
        'fallback_cb'     => 'wp_page_menu',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>'
    );
    ?>
     
    <?php wp_nav_menu( $defaults ); ?>
    
    /* Output */
    
    <div id="navbar" class="navbar-collapse collapse">
    	<ul id="menu-main" class="nav navbar-nav navbar-right">
    		<li id="menu-item-108" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-2 current_page_item menu-item-108"><a href="http://www.example.com/">Home</a></li>
    	</ul>
    </div>
  • 5 years-11 months

    how to add a custom fields to wordpress pages and custom post type

    • Category : wordpress
    • Location : Chandigarh, India
    • Posted On : Feb 20, 2018
    • Posted by : Vikas

    The hook allows meta box registration for any post type. Passes two parameters: $post_type and $post. Note: You can also use add_meta_boxes_{post_type} for best practice, so your hook will only run when editing a specific post type. This will only receive 1 parameter - $post.

    Add this to functions.php
    add_action( 'add_meta_boxes', 'gp_add_meta_boxes' );
    function gp_add_meta_boxes() {
        add_meta_box( 'gp_product', 'Products Options', 'gp_products_callback', 'review', 'normal', 'high' );
    }
    
    function gp_products_callback( $post ) {
        $fname = get_post_meta( $post->ID, 'fname', true );
    
    // reset choices
    	$field['choices'] = array();
    	
    	$users = get_users();
    	?>
    	<select name="cust_user"></select>
    	<?php
    	foreach ($users as $user) {
    		$field[ $user->ID ] = $user->display_name;
    	}
    
        ?>
        <p>First Name: <input type="text" name="fname" value="<?php echo $fname; ?>"></p>
        <?php
    }
     
  • 5 years-11 months

    How to WooCommerce state field (billing or shipping) not required on checkout page

    • Category : wordpress
    • Location : Chandigarh, India
    • Posted On : Feb 15, 2018
    • Posted by : Vikas

    Try this code in your functions.php file

    add_filter( 'woocommerce_billing_fields', 'woo_filter_state_billing', 10, 1 );
    add_filter( 'woocommerce_shipping_fields', 'woo_filter_state_shipping', 10, 1 );
    function woo_filter_state_billing( $address_fields ) { 
      $address_fields['billing_state']['required'] = false;
    	return $address_fields;
    }
    function woo_filter_state_shipping( $address_fields ) { 
    	$address_fields['shipping_state']['required'] = false;
    	return $address_fields;
    }
     
  • 5 years-11 months

    How to Update PHP cookie or Update if not set and get cookie all values using codeigniter

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Jan 11, 2018
    • Posted by : Vikas

    A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

    Note: The setcookie() function must appear BEFORE the <html> tag.
    public function add_cookies($name,$value="",$time=3600) {
    	$this->load->helper('cookie');
    	if($value=="") {
    		return json_decode(get_cookie($name),true);
    	}
    	$val=$value;
    	if($val!="") {
    		$search1=get_cookie($name);
    		if($search1!="") {
    			$search1=json_decode($search1,true);
    			if(!in_array($val, $search1)) {
    				$search1[]=$val;
    				$cookie= array(
    				       'name'   => $name,
    				       'value'  => json_encode($search1),
    				       'expire' => $time,
    				   );
    				set_cookie($cookie);
    			}
    		} else {
    			$value=array();
    			$value[]=$val;
    			$cookie= array(
    			       'name'   => $name,
    			       'value'  => json_encode($value),
    			       'expire' => $time,
    			   );
    			set_cookie($cookie);
    		}
    	}
    	return json_decode(get_cookie($name),true);
    }
     
  • 5 years-11 months

    How to Connect with MySQLi or PDO Server through PHP

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Jan 10, 2018
    • Posted by : Vikas

    PHP you can easily do this using the mysqli_connect() function. All communication between PHP and the MySQL database server takes place through this connection. The basic syntaxes for connecting to MySQL using MySQLi and PDO extensions:

    Syntax: MySQLi, Procedural way
    $con = mysqli_connect("hostname", "username", "password", "database");
    Syntax: MySQLi, Object Oriented way
    $con = new mysqli("hostname", "username", "password", "database");
    Syntax: PHP Data Objects (PDO) way
    $pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password"); 
    Example (mysqli)

    Perform queries against the database:
    <?php
    $con=mysqli_connect("localhost","your_user","your_password","your_db");
    // Check connection
    if(mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    // Perform queries
    mysqli_query($con,"SELECT * FROM yourtable");
    mysqli_query($con,"INSERT INTO yourtable (FName,LName,Age)
    VALUES ('Glen','Quagmir',65)");
    
    mysqli_close($con);
    ?> 
    Example (PDO)

    Perform queries against the database:
    <?php
    $servername = "localhost";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_DBPDO";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // prepare sql and bind parameters
        $stmt = $conn->prepare("INSERT INTO yourGuests (ftname, lname, email)
        VALUES (:ftname, :lname, :email)");
        $stmt->bindParam(':ftname', $firstname);
        $stmt->bindParam(':lname', $lastname);
        $stmt->bindParam(':email', $email);
    
        // insert a row
        $firstname = "John";
        $lastname = "Doe";
        $email = "john@domain.com";
        $stmt->execute();
    
        // insert another row
        $firstname = "Julie1";
        $lastname = "Dooley1";
        $email = "julie1@domain.com";
        $stmt->execute();
    
        echo "New records added successfully";
        }
    catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
    $conn = null;
    ?> 
     
  • 5 years-11 months

    Anybody know that how to create HTML to PDF in PHP with phpToPDF

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Jan 10, 2018
    • Posted by : Vikas

    Now generate 'A5' sized PDF from html and display it view. The PDF name will be 'simple_any_name.pdf'.

    <?php
     // INCLUDE THE phpToPDF.php FILE
    require("phpToPDF.php"); 
    
    // PUT YOUR HTML IN A VARIABLE
    $my_html="<HTML>
    <h2>Test HTML 02</h2><br><br>
    <div style=\"display:block; padding:20px; border:2pt solid:#FE9A2E; background-color:#F6E3CE; font-weight:bold;\">
    phpToPDF is pretty cool! <br><br>
    [This was orange, but I set the PDF option to monochrome (Black & White)]
    </div><br><br>
    For more examples, visit us here --> https://www.dorcode.com/
    </HTML>";
    
    // SET YOUR PDF OPTIONS -- FOR ALL AVAILABLE OPTIONS, VISIT HERE:  http://phptopdf.com/documentation/
    $pdf_options = array(
      "source_type" => 'html',
      "source" => $my_html,
      "action" => 'view',
      "color" => 'monochrome',
      "page_orientation" => 'landscape',
      "file_name" => 'simple_any_name.pdf');
    
    // CALL THE phpToPDF FUNCTION WITH THE OPTIONS SET ABOVE
    phptopdf($pdf_options);
    
    ?> 
     
  • 5 years-11 months

    HTML5 Form Validation With the pattern (Regex) Attribute in html

    • Category : html
    • Location : Chandigarh, India
    • Posted On : Dec 19, 2017
    • Posted by : Vikas

    This is another Client Side Validation strategy No JavaScript or jQuery required, Thanks to HTML5 in light of the fact that approvals should now be possible utilizing HTML5 without coding of javascript or any server side dialect, utilizing HTML5 you can approve frames with design, Forms must be approve either utilizing customer side or server side since it causes you to gather redress information or substantial shape esteems from the clients, you can't trust clients aimlessly, how about we see it.

    pattern="[A-Za-z] " accepts only capital or small letters. 
    <label>Name : (letters only)*</label>
    <input type="text" pattern="[A-Za-z] " title="only letters" required />
    
    pattern="[a-z0-9._% -] @[a-z0-9.-] \.[a-z]{2,4}$" accepts valid email address 
    <label>E-mail : (xyz@zyx.com)*</label>
    <input type="email" pattern="[a-z0-9._% -] @[a-z0-9.-] \.[a-z]{2,4}$" title="xyz@something.com" required />
    
    pattern="https?://. " required title="https://dorcode.com" accepts valid web url starting with http://. 
    <label>website : (https://dorcode.com)*</label>
    <input type="url"  pattern="https?://. " title="https://dorcode.com" required />
    
    pattern="[0-9] " accepts only numbers 0, 1, 2.... 
    <label>pin code : (numbers only)</label>
    <input type="text" pattern="[0-9] " title="numbers only" required />
    
    pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" accepts one number one upper and lower case letters with 8 or more chars. 
    <label>password : (at least 6 chars)</label>
    <input type="password" pattern=".{6,}" title="Six or more characters" required />
    
    pattern="^\d{10}$" accepts only numeric values with 10 digit. 
    <label>phone no : (10 chars)</label>
    <input type="tel" pattern="^\d{10}$" title="10 numeric characters only" required />
    
    pattern="^[a-zA-Z][a-zA-Z0-9-_\.]{5,12}$" accepts alphanumeric values letters and digits. 
     
  • 5 years-11 months

    Wordpress administrator page not showing up template name in template dropdown

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Nov 22, 2017
    • Posted by : Vikas

    There's a bug in Wordpress 4.9, I discovered this temporary super code. I plan on uninstalling it once they fix the bug, but it works great in the meantime!

    global $wpdb;
    $wpdb->query( "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE '_transient_files_%' LIMIT 1" );
     
  • 5 years-11 months

    Dynamically loading an external JavaScript or CSS file using function

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Nov 06, 2017
    • Posted by : Vikas

    To load a .js or .css file dynamically, in a head section, it means using DOM methods to first create a new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together

    <script type="text/javascript">
    // function
    function loadheadfile(filename, filetype){
    	if(filetype=="js"){
    		var fileref=document.createElement('script')
    		fileref.setAttribute("type","text/javascript")
    		fileref.setAttribute("src", filename)
    	}
    	else if(filetype=="css") {
    		var fileref=document.createElement("link")
    		fileref.setAttribute("rel", "stylesheet")
    		fileref.setAttribute("type", "text/css")
    		fileref.setAttribute("href", filename)
    	}
    	if(typeof fileref!="undefined")
    		document.getElementsByTagName("head")[0].appendChild(fileref)
    }
    
    
    // call function
    loadheadfile('https://tsuyoshiwada.github.io/sweet-scroll/lib/icomoon/style.css','css');
    </script>
     
  • 5 years-11 months

    How do I separate all YouTube video ids and links in a string using a regex

    • Category : php
    • Location : Chandigarh, India
    • Posted On : Oct 06, 2017
    • Posted by : Vikas

    YouTube video Link may be encountered in a variety of formats:

    1.     latest short format: http://youtu.be/NLqAF9hrVbY
    2.     iframe: http://www.youtube.com/embed/NLqAF9hrVbY
    3.     iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
    4.     object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
    5.     object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
    6.     watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
    7.     users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
    8.     ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
    9.     any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
    10.     more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
    11.     query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be
    12.     nocookie domain: http://www.youtube-nocookie.com
    function convertYoutube($string) {
    	$pattern='~(?#!js YouTubeId Rev:20160125_1800)
            # Match non-linked youtube URL in the wild. (Rev:20130823)
            https?://          # Required scheme. Either http or https.
            (?:[0-9A-Z-] \.)?  # Optional subdomain.
            (?:                # Group host alternatives.
              youtu\.be/       # Either youtu.be,
            | youtube          # or youtube.com or
              (?:-nocookie)?   # youtube-nocookie.com
              \.com            # followed by
              \S*?             # Allow anything up to VIDEO_ID,
              [^\w\s-]         # but char before ID is non-ID char.
            )                  # End host alternatives.
            ([\w-]{11})        # $1: VIDEO_ID is exactly 11 chars.
            (?=[^\w-]|$)       # Assert next char is non-ID or EOS.
            (?!                # Assert URL is not pre-linked.
              [?=& %\w.-]*     # Allow URL (query) remainder.
              (?:              # Group pre-linked alternatives.
                [\'"][^<>]*>   # Either inside a start tag,
              | </a>           # or inside <a> element text contents.
              )                # End recognized pre-linked alts.
            )                  # End negative lookahead assertion.
            [?=& %\w.-]*       # Consume any URL (query) remainder.
            ~ix';
    	preg_match_all($pattern,$string,$match);
    	$res=array();
    	$res['youtube']=$match;
    	$res['text']=preg_replace($pattern, '', $string);
    	return $res;
    }
    $text = "php find youtube link in string. How do I find all YouTube video ids in a string using a regex https://www.youtube.com/watch?v=ItTjUrTZ_JE Find youtube Link in PHP string and Convert it into embed code? Well, you need to filter out the youtube links first and put them into an string. Next you need to find out the youtube links of the url which is very easy. Use this script:";
    
    $all=convertYoutube($text);
    
    //print_r($all);
    
    echo $all['youtube'][1][0];	
    // ItTjUrTZ_JE
    
    echo $all['youtube'][0][0];	
    // https://www.youtube.com/watch?v=ItTjUrTZ_JE
    
    echo $all['text'];	
    // php find youtube link in string. How do I find all YouTube video ids in a string using a regex Find youtube Link in PHP string and Convert it into embed code? Well, you need to filter out the youtube links first and put them into an string. Next you need to find out the youtube links of the url which is very easy. Use this script: