Write HTML in PHP

Examples for : Write HTML in PHP

With print command , you can output HTML code inside php.

Sample code :

print("This is point to print.");

To use quotes inside print command , use \" inside code.

print("Visit Google");

With echo , html output can be done inside php.

echo "

This is HTML code inside echo syntax inside php

";

WooCommerce: Easily Get Product Info (ID, SKU, $) from $product Object

I have been wanting to publish this guide for a long while. As a freelancer, every day I repeat many operations that make me waste time – and one of them is indeed "How to get ___ if we have the $product variable/object?".
For example, "How can we get the product SKU?? Or "How can we get the product short description"? Or maybe the product stock level, shipping class, tax class, price, regular price, sale price, and so on.. Hopefully this article will save you time
Get Product Info

1. If we have access to $product

// Get Product ID
 
$product->get_id(); (fixes the error: "Notice: id was called incorrectly. Product properties should not be accessed directly")
 
// Get Product General Info
 
$product->get_type();
$product->get_name();
$product->get_slug();
$product->get_date_created();
$product->get_date_modified();
$product->get_status();
$product->get_featured();
$product->get_catalog_visibility();
$product->get_description();
$product->get_short_description();
$product->get_sku();
$product->get_menu_order();
$product->get_virtual();
get_permalink( $product->get_id() );
 
// Get Product Prices
 
$product->get_price();
$product->get_regular_price();
$product->get_sale_price();
$product->get_date_on_sale_from();
$product->get_date_on_sale_to();
$product->get_total_sales();
 
// Get Product Tax, Shipping & Stock
 
$product->get_tax_status();
$product->get_tax_class();
$product->get_manage_stock();
$product->get_stock_quantity();
$product->get_stock_status();
$product->get_backorders();
$product->get_sold_individually();
$product->get_purchase_note();
$product->get_shipping_class_id();
 
// Get Product Dimensions
 
$product->get_weight();
$product->get_length();
$product->get_width();
$product->get_height();
$product->get_dimensions();
 
// Get Linked Products
 
$product->get_upsell_ids();
$product->get_cross_sell_ids();
$product->get_parent_id();
 
// Get Product Variations
 
$product->get_attributes();
$product->get_default_attributes();
 
// Get Product Taxonomies
 
$product->get_categories();
$product->get_category_ids();
$product->get_tag_ids();
 
// Get Product Downloads
 
$product->get_downloads();
$product->get_download_expiry();
$product->get_downloadable();
$product->get_download_limit();
 
// Get Product Images
 
$product->get_image_id();
get_the_post_thumbnail_url( $product->get_id(), 'full' );
$product->get_gallery_image_ids();
 
// Get Product Reviews
 
$product->get_reviews_allowed();
$product->get_rating_counts();
$product->get_average_rating();
$product->get_review_count();
 
// source: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

2. If we have access to $product_id

If we have access to the product ID (once again, usually the do_action or apply_filters will make this possible to we), we have to get the product object first. Then, do the exact same things as above.
// Get $product object from product ID
 
$product = wc_get_product( $product_id );
 
// Now you have access to (see above)...
 
$product->get_type();
$product->get_name();
// etc.
// etc.

3. if we have access to the Order object or Order ID

How to get the product information inside the Order? In this case you will need to loop through all the items present in the order, and then apply the rules above.
// Get $product object from $order / $order_id
 
$order = new WC_Order( $order_id );
$items = $order->get_items();
 
foreach ( $items as $item ) {
 
    $product = wc_get_product( $item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}

4. You have access to the Cart object

How to get the product information inside the Cart? In this case, once again, you will need to loop through all the items present in the cart, and then apply the rules above.
// Get $product object from Cart object
 
$cart = WC()->cart->get_cart();
 
foreach( $cart as $cart_item ){
 
    $product = wc_get_product( $cart_item['product_id'] );
 
    // Now you have access to (see above)...
 
    $product->get_type();
    $product->get_name();
    // etc.
    // etc.
 
}

Show original image rather than thumbnail for product on shop page in woocommerce

Solution for : Show original image rather than thumbnail for product on shop page in woocommerce

//show full image on wocommerece list items
remove_action('woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action('woocommerce_before_shop_loop_item_title', 'new_woocommerce_template_loop_product_thumbnail', 10);

function new_woocommerce_template_loop_product_thumbnail() {
 $imgurl= wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
 echo '';
}

Woocommerce get category image full size

Solution for : Woocommerce get category image full size
We can use this wp_get_attachment_image_src function to achieve the goal.
$prod_categories = get_terms( 'product_cat', array(
        'orderby'    => 'name',
        'order'      => 'ASC',
        'hide_empty' => true
    ));

    foreach( $prod_categories as $prod_cat ) :
        $cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
        $shop_catalog_img = wp_get_attachment_image_src( $cat_thumb_id, 'full' );
        $term_link = get_term_link( $prod_cat, 'product_cat' );?>

         echo '
'; echo $prod_cat->name; echo '----'; echo ''; echo '
'; endforeach; wp_reset_query();

Exclude multiple terms using get_terms() function

Soution for : exclude multiple terms using get_terms() function

With get_terms(), the exclude parameter takes an array of term IDs, so just add the second term to the array:

$terms = get_terms( 'product_cat', array(
    'orderby'    => 'name',
    'order'      => 'ASC',
    'hide_empty' => 0,
    'exclude' => array( 23 ),
    ));

echo '
  • Category:
  • '; foreach ( $terms as $term ) { echo '
  • '.$term->name.'
  • '; }

    WooCommerce Notice Messages, how do I edit them?

    I'm trying to figure out where WooCommerce creates it's messages for when there is a success, error or notice in WooCommerce. I want to edit those messages to fit the scenario more neatly and also edit the HTML. Where are these messages located and how do I edit them?

    Solution code for : WooCommerce Notice Messages, how do I edit them?

    Many of them are directly in the plugin files - unfortunately. Some messages are tied to filter hooks that allow you to edit them without messing with plugin files but that's not always the case.

    The message you wanted to change was "Product Name was successfully added to your cart". This one is set in the function wc_add_to_cart_message in wc-cart-functions.php and this function allows you to change it using a filter:

    wc_add_notice( apply_filters( 'wc_add_to_cart_message', $message, $product_id ) );
    

    So in your functions.php file you could add something like:

    add_filter('wc_add_to_cart_message', 'handler_function_name', 10, 2);
    function handler_function_name($message, $product_id) {
        return "Thank you for adding product" . $product_id;
    }
    

    Setting variable in header.php but not seen in footer.php

    In wordpress , I set a variable in header.php
    $var= 'anything';
    
    but in footer.php when I echo it
    echo $var;
    
    I got no thing printed. why?
    Solution for : setting variable in header.php but not seen in footer.php

    You're not in the same scope, as the header and footer files are included in a function's body. So you are declaring a local variable, and referring to another local variable (from another function).

    So just declare your variable as global:
    $GLOBALS[ 'var' ] = '...';
    
    Then you can echo it globally.
    echo $GLOBALS[ 'var' ];
    

    How To Create Custom User Role in Wordpress

    Soution code for : How To Create Custom User Role in Wordpress

    You can use add role function like

    add_role( $role, $display_name, $capabilities );
    

    Example

    add_role('basic_contributor', 'Basic Contributor', array(
        'read' => true, // True allows that capability
        'edit_posts' => true,
        'delete_posts' => false, // Use false to explicitly deny
    ));
    

    Add a custom class name to Wordpress body tag

    Soution code for : Add a custom class name to Wordpress body tag

    We can use the body_class filter, like so:

    function my_plugin_body_class($classes) {
        $classes[] = 'foo';
        return $classes;
    }
    
    add_filter('body_class', 'my_plugin_body_class');
    

    Although, obviously, our theme needs to call the corresponding body_class function.

    How to horizontally center a <div> using CSS?

    How can we horizontally center a <div> within another <div> using CSS?

    Foo foo

    Solution code for : How to horizontally center a <div> using CSS?

    We can apply this CSS to the inner <div>:

    HTML

    Foo foo

    CSS

    #inner {
      width: 50%;
      margin: 0 auto;
    }
    

    Of course, we don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

    If we are targeting IE8+, it might be better to have this instead:

    HTML

    Foo foo

    CSS

    #inner {
      display: table;
      margin: 0 auto;
    }
    

    It will make the inner element center horizontally and it works without setting a specific width.

    CSS Floating Menu

    Creating a floating menu is very simple and quite easy. The operative code is position:fixed .

    Example of a Floating Menu

    The menu below an example of a floating menu. As we scroll down the page, we will notice the menu stays fixed in the same position on the page.

    HTML

    
     

    Scroll down and watch the menu remain fixed in the same position, as though it was floating.

    CSS

     
      .floating-menu {
        font-family: sans-serif;
        background: yellowgreen;
        padding: 5px;;
        width: 130px;
        z-index: 100;
        position: fixed;
        bottom: 0px;
        right: 0px;
      }
    
      .floating-menu a, 
      .floating-menu h3 {
        font-size: 0.9em;
        display: block;
        margin: 0 0.5em;
        color: white;
      } 
    
    

    We can use the top, bottom, left, and/or right to position the menu exactly where we want it on the page.

    WP_query using meta_query for an ACF checkbox field

    Problem : WP_query using meta_query for an ACF checkbox field

    I’m using WP_Query to show a list of results. I want to filter these based on an ACF checkbox field. I think that I’m getting muddled up with how to correctly parse the ‘value’ array from my ACF field.

    Below solution helped me.

    Soution code for : WP_query using meta_query for an ACF checkbox field

    // Get the selected options
    $my_acf_checkbox_field_arr = get_field('my_checkbox'); // OR  $my_acf_checkbox_field_arr =array('checkbox-value1','checkbox-value2');
    
    // Build the meta query based on the selected options
    $meta_query = array('relation' => 'OR');
    foreach( $my_acf_checkbox_field_arr as $item ){
        $meta_query[] = array(
            'key'     => 'checkbox',
            'value'   => $item,
            'compare' => 'LIKE',
        );
    }
    
    // args
    $args = array(
     'numberposts' => -1,
     'post_type'  => 'my-cpt',
     'meta_query' => $meta_query,
    );
    
    $the_query = new WP_Query( $args );
    

    Wordpress session variable not working

    Problem : Wordpress session variable not working

    I have an issue with a WordPress session.

    In the file themes/theme-name/header.php I wrote this code:

    session_start();
    
    if(isset($_SESSION['var'])) {
          echo 'Welcome'; 
    }  else if(isset($_POST['var'])) {
           $_SESSION['var'] = $_POST['var']; 
    } else {
           echo 'No access...';
           exit; 
    }
    

    Solution For : Wordpress session variable not working

    Just hook a function on "init" in your functions.php like this :

    function ur_theme_start_session()
    {
        if (!session_id())
            session_start();
    }
    add_action("init", "ur_theme_start_session", 1);
    

    Then we can use our session variables.

    I hope that help you.

    How to include pagination in a Wordpress Custom Post Type Query

    Solution for : How to include pagination in a Wordpress Custom Post Type Query

    If we have to get the list for custom post type "project". Below is simple code to achieve our goal.

    $the_query = new WP_Query( 
     array('posts_per_page'=>20,
     'post_type'=>'project',
     'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
     );
     
     
    while ($the_query -> have_posts()) : $the_query -> the_post();
    
    echo '';
    endwhile; 
     
    $big = 999999999; // need an unlikely integer
    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $the_query->max_num_pages
    ) );
    
    wp_reset_postdata();
    

    Get cart item name, quantity all details woocommerce

    Solution for : Get cart item name, quantity all details woocommerce.

    I am trying to send the woocommerce cart items to third party shipping tool. I need the item name, quantity and individual price to be sent to the third party. How can this be achieved?

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    
    foreach($items as $item => $values) { 
     $_product =  wc_get_product( $values['data']->get_id()); 
     echo "".$_product->get_title().'  
    Quantity: '.$values['quantity'].'
    '; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."
    "; }

    To get Product Image and Regular & Sale Price:

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();
    
    foreach($items as $item => $values) { 
     $_product =  wc_get_product( $values['data']->get_id() );
     //product image
     $getProductDetail = wc_get_product( $values['product_id'] );
     echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )
    
     echo "".$_product->get_title() .'  
    Quantity: '.$values['quantity'].'
    '; $price = get_post_meta($values['product_id'] , '_price', true); echo " Price: ".$price."
    "; /*Regular Price and Sale Price*/ echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."
    "; echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."
    "; }

    WooCommerce - get category for product page

    Solution for : WooCommerce - get category for product page

    A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    foreach ($terms as $term) {
        $product_cat_id = $term->term_id;
        break;
    }
    

    Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

    echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' );
    
    

    How to remove woocommerce tab?

    Solution for : How to remove woocommerce tab?

    While CSS is great, if the stylesheet doesn't load correctly, you could end up showing someone tabs without meaning to. It is best to remove the content before loading (server side), by using a filter, as you had mentioned.

    See code below as provided from Woothemes for unsetting data tabs.
    EDIT Place within the functions.php file inside your theme.

    add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
    
    function woo_remove_product_tabs( $tabs ) {
        unset( $tabs['description'] );          // Remove the description tab
        unset( $tabs['reviews'] );          // Remove the reviews tab
        unset( $tabs['additional_information'] );   // Remove the additional information tab
        return $tabs;
    }
    

    Override WooCommerce Frontend Javascript

    Solution for : Override WooCommerce Frontend Javascript

    I had the same problem except with add-to-cart.js. Simple solution is to DEQUEUE the woocommerce script and ENQUEUE your replacement. In my case I added the following to my functions.php:

    wp_dequeue_script('wc-add-to-cart');
    wp_enqueue_script( 'wc-add-to-cart', get_bloginfo( 'stylesheet_directory' ). '/js/add-to-cart-multi.js' , array( 'jquery' ), false, true );
    

    You would want to DEQUEUE the 'wc-add-to-cart-variation' script. I don't think you have to ENQUEUE with the same name, but I couldn't see a reason not to.

    Hope this helps.

    If you're using WordPress Version 4.0.1 and WooCommerce Version 2.2.10. You can use the following scripts:

    wp_deregister_script('wc-add-to-cart');
    wp_register_script('wc-add-to-cart', get_bloginfo( 'stylesheet_directory' ). '/js/add-to-cart-multi.js' , array( 'jquery' ), WC_VERSION, TRUE);
    wp_enqueue_script('wc-add-to-cart');
    

    Short Description in checkout woocommerce wordpress

    Solution for : How do you add a short description for each product to the checkout page in Woocommerce?

    The filter woocommerce_get_item_data can be used for that.

    Like so:

    add_filter( 'woocommerce_get_item_data', 'wc_checkout_description_so_15127954', 10, 2 );
    
    function wc_checkout_description_so_15127954( $other_data, $cart_item )
    {
        $post_data = get_post( $cart_item['product_id'] );
        $other_data[] = array( 'name' =>  $post_data->post_excerpt );
        return $other_data;
    }
    

    Note that maybe some kind of checking will be needed, e.g., make sure this filter is only called when actually viewing the Checkout page, as I don't know if it'll be called in other instances.

    Woocommerce - Get SKU in product single page

    Solution for : To get SKU in product single page in woocommerce

    Below is code/function To get SKU in product single page in woocommerce

    get_sku() is a method of the WC_Product class, so you need to have a product on which to call it, like this:

    echo $product->get_sku();
    

    This should work if you are inside the WooCommerce product loop, and is what is used in the WooCommerce template files. If you don't already have a reference to the product object, you may need to add the following line at the top of the file in order to access it:

    global $product;
    

    Get custom attribute in woocommerce

    Solution for : Get custom attribute in woocommerce

    Below is code/function to Get custom attribute in woocommerce.

    If attribute key is "pa_specification"

    function woo_new_product_tab_content() {
        // The new tab content    
        global $post; 
    
        $product_id = $post->ID;
    
        $product = new WC_Product( $product_id );
    
        $pa_value = $product->get_attribute('pa_specification'); 
    
        echo $pa_value; 
    
    }
    

    Woocommerce code get list products

    Solution for : Woocommerce code get list products

    Below code will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement

     $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 10,
            'product_cat'    => 'hoodies'
        );
    
        $loop = new WP_Query( $args );
    
        while ( $loop->have_posts() ) : $loop->the_post();
            global $product;
            echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
        endwhile;
    
        wp_reset_query();
    

    WooCommerce- change admin date format

    Solution for : WooCommerce- change admin date format

    I would like to change the WooCommerce date format from Y/m/d to d/m/Y. I have the Print invoice plug-in, and the dates are in the y/m/d format as taken from the date ordered in WooCommerce.

    You also have to change the value of '$t_time' variable using the same 'post_date_column_time' filter.You have to return two values ($t_time and $h_time) using two separate callback functions. Your code will work when you add following callback on same filter in addition to your code.

    add_filter( 'post_date_column_time' ,'woo_custom_post_date_column_time_withDate' );
    
    function woo_custom_post_date_column_time_withDate( $post ) {  
    $t_time = get_the_time( __( 'd/m/Y g:i:s A', 'woocommerce' ), $post );
     return $t_time; 
    }
    

    Also check the format you have set into the call back function, change it to 'd/m/Y' since you require it.

    Woocommerce replace 'add to cart' button with custom button/ product link

    Solution for : Woocommerce replace add to cart button with custom button/link

    Replacing the button add to cart by a link to the product in Shop and archives pages for woocommerce 3+

    add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
    function replacing_add_to_cart_button( $button, $product  ) {
        $button_text = __("View product", "woocommerce");
        $button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    
        return $button;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested on WooCommerce 3+ and works. You can customize the text of button and you will get something like:

    Removing index.php from a URL path in XAMPP for Windows

    STEP 1: Create .htaccess using the command prompt in Windows

    1. Open command prompt

    2. In the command prompt, change the working directory to the CodeIgniter directory i.e. the directory that contains the application and system directories

      cd C:\xampp\htdocs\site_folder

    3. Type copy con .htaccess to create a .htaccess file in the current working directory

    4. Press [ENTER] to append an empty line

    5. Type the following code:

      <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php/$1 [L]
      </IfModule>
      
    6. Finally, enter CTRL + Z to append the data to the .htaccess file and hit [ENTER] to save

    STEP 2: Configure mod_rewrite in httpd.conf

    1. Locate the httpd.conf file in the Apache sub-directory C:\xampp\apache\conf\httpd.conf

    2. Uncomment the following line from: #LoadModule rewrite_module modules/mod_rewrite.so

      to

      LoadModule rewrite_module modules/mod_rewrite.so

    3. Save the changes to the file

    STEP 3: Configure config.php in you site_folder (CodeIgniter) folder

    1. Locate config.php C:\xampp\htdocs\site_folder\system\application\config

    2. Change the following line from: $config['index_page'] = 'index.php';

      to

      $config['index_page'] = '';