Categories
Code Snippets PHP Wordpress

Redirect to shop if cart is empty

function cart_empty_redirect_to_shop() {
    global $woocommerce;
    
    $shop_page_url = get_permalink( woocommerce_get_page_id( 'shop' ) );

    if ( is_page('cart') && !sizeof($woocommerce->cart->cart_contents) ) {
        wp_redirect( $shop_page_url, 301 ); 
        exit;
    }
}
# -*- coding: utf-8 -*-
"""
Created on Sat Apr  3 14:12:04 2021

@author: KG
"""

# Import modules
import pandas as pd
import math
from pulp import *

# Define variables
current_cost = 0.0
food_dict = {}

# Load food data into food pandas dataframe
food = pd.read_excel('diet.xls', skipfooter=3)

# Get a preview of our food dataframe
print(food)

# Create a list of Protein food choices
protein_list = ['Roasted Chicken', 'Poached Eggs', 'Scrambled Eggs', 'Bologna,Turkey', 'Frankfurter, Beef', 'Ham,Sliced,Extralean', 'Kielbasa,Prk', 'Pizza W/Pepperoni', 'Hamburger W/Toppings', 'Hotdog, Plain', 'Pork', 'Sardines in Oil', 'White Tuna in Water', 'Chicknoodl Soup', 'Splt Pea&Hamsoup', 'Beanbacn Soup,W/Watr']

# Load minimum and maximum values into the min_max table
min_max = pd.read_excel('diet.xls', skiprows = food.shape[0]+1, usecols=("C:N"), header=0)
column_names = pd.read_excel('diet.xls', usecols=("C:N"), nrows=0)
min_max = pd.DataFrame(data=min_max.values, columns=column_names.columns)

# Get a preview of our min_max file
print(min_max)

# Convert our food dataframe to a list
food_data = food.values.tolist()
food_list = [x[0] for x in food_data]
    
# Create the Optimization Problem
prob = LpProblem('DietProblem', LpMinimize)

# Create the variables using LpVariable.dicts
food_vars = LpVariable.dicts( "Food", food_list, lowBound = 0 ) # for food variables
food_chosen = LpVariable.dicts("Chosen",food_list,0,1,cat='Integer') # for chosen foods
protein_chosen = LpVariable.dicts("Protein",protein_list,0,1,cat='Integer') # for protein foods chosen

# Add the Objective Function for cost
costs = {x[0]:x[1] for x in food_data}
prob += lpSum( costs[i] * food_vars[i] for i in food_list )

# Add each variable to the Optimization Problem by looping over the min_max dataframe
for v in range(len(min_max.columns[1:])):
    
    # Get the variable name from the min_max dataframe
    variable = min_max.columns[1:][v]
    
    # Add the variable to the Optimization Problem
    food_dict[variable] = {x[0]:x[v+3] for x in food_data} 
    prob += lpSum( food_dict[variable][i] * food_vars[i] for i in food_list ) >= min_max[variable][0] # >= min value for the variable
    prob += lpSum( food_dict[variable][i] * food_vars[i] for i in food_list ) <= min_max[variable][1] # <= max value for the variable
        

# Add the Constraint where each food much be atleast 1/10 of the total serving
for f in food_list:
    prob += food_vars[f] >= food_chosen[f] * 0.10


# Add the Constraint of selecing either Celery or Frozen Broccoli
prob += food_chosen['Frozen Broccoli'] + food_chosen['Celery, Raw'] <= 1

# Add the Constraint of selecting atleast 3 choices from the list of Protein items
prob += lpSum([food_chosen[p] for p in protein_list]) >= 3

# Store the solution of the Optimization Problem
soln = prob.solve()

# Get the Status of the Optimization Problem
print( LpStatus[prob.status])

# Get the Amounts of the Foods Chosen 
for v in prob.variables():
    if v.varValue != 0:
        print( f"{v.name} = {v.varValue:.2f}")

# Get the Final Cost of Food Chosen
print(f"Cost: {value(prob.objective)}")

 

Categories
Blog Code Snippets PHP Wordpress

Remove DNS-Prefetch Links on WordPress Site Without Plugin

// Remove dns-prefetch Link from WordPress Head (Frontend)
remove_action( 'wp_head', 'wp_resource_hints', 2 );

 

Categories
Blog Code Snippets PHP Wordpress

WordPress Plugin Error – Notice: Trying to get property of non-object in…

I’m getting this error in relation to the ‘Grid & List toggle for Woocommerce’ plugin, specifically this file:

/wp-content/plugins/grid-list-toggle-for-woocommerce/woocommerce_grid_list.php on line 115

 

Basically, the error was corrected by surrounding the code after global $post with the following statement:

if ( is_object( $post )) {

Categories
Blog Code Snippets PHP Wordpress

Display Product Categories with Thumbnail Image

Use shortcode: [show-product-categories-with-image]

Add the following to your functions.php file.

function showProductCat() {

$cat_args = array(
'orderby' => 'name',
'order' => 'asc',
'hide_empty' => true,
);

$product_categories = get_terms( 'product_cat', $cat_args );

$result = "<div class='product-categories-with-image'>";

if( !empty($product_categories) ){

foreach ($product_categories as $key => $category) {

$thumb_id = get_woocommerce_term_meta( $category->term_id, 'thumbnail_id', true );
$term_img = D0d_get_attachment_image_src( $thumb_id, 'thumbnail', true );

$cat_img = "";

if ($term_img[3]) {
$cat_img = "<img src='". $term_img[0] ."' width='" . $term_img[1] . "' height='" . $term_img[2] . "' />";
}

$result = $result . '<a href="'.get_term_link($category).'" >'
. $cat_img
. $category->name
. '</a><br/>';
}

}

$result = $result . "</div>";

return $result;
}
add_shortcode('show-product-categories-with-image', 'showProductCat');
Categories
Code Snippets PHP Wordpress

Redirect for a Specific Page on WordPress

Here’s a snippet of code to redirect users who land on a specific page of your wordpress site.

You will need the page id. Add it to your functions.php file.

The code below redirect users to my site. 🙂

function redirect_to_another_page() {
   $page_id_to_redirect = 119; //enter page id here
   $destination = 'https://kimberleydurrant.com'; //enter destination url here

   if ( is_page($page_id_to_redirect) ) {
      wp_redirect( $destination, 301 );
      exit;
   }
}
add_action( 'template_redirect', 'redirect_to_another_page' );
Categories
Blog Code Snippets PHP Wordpress

WordPress – Deactivate a Sidebar or Widgetized Area

Here’s how to deactive a Sidebar or Widgetized Area in WordPress so it won’t show on the website and neither will it show on the Widgets section of the wordpress backend.

First, get the name of the sidebar, you may need to check the theme functions file to get exactly it is.

In this case, we will assume that the sidebar name is ‘sidebar-1’.

Add the code below to your functions file.

function remove_some_widgets(){

	// Unregister sidebar
	unregister_sidebar( 'sidebar-1' );

}
add_action( 'widgets_init', 'remove_some_widgets', 11 );
Categories
Blog Code Snippets PHP Wordpress

WordPress – Embed a Visual Composer page with CSS Styles

Here’s how to embed a page created with Visual Composer onto another page with the page CSS styles included. You can add this code to either the header or footer file of your theme, or another theme file for that matter.

In other words, include a Visual Composer Page as a header, footer or sidebar.

First step: note the id of the page to be embedded. In our example, let’s assume the id of the page to be embedded is 899.

Use this snippet and put the id into the first line of code as indicated below.

$id = 899;	//Assumes the page id to be embedded is 899
$p = get_page($id);


//Loads page styles
$shortcodes_custom_css = get_post_meta( $id, '_wpb_shortcodes_custom_css', true );
if ( ! empty( $shortcodes_custom_css ) ) {
    echo '<style type="text/css" data-type="vc_shortcodes-custom-css-'.$id.'">';
        echo $shortcodes_custom_css;
    echo '</style>';
}

//Loads page content
echo apply_filters('the_content', $p->post_content);

 

Categories
PHP Wordpress

Load / Enqueue the latest version of css and javascript files

Add the following code to your functions.php file to load or enqueue the most recent child theme style.css file or any css/javascript file.

function my_custom_files() {

  //use the current date and time as the file version
  $cache_buster = date("YmdHi");
  
  wp_register_style( 'childstyle', get_stylesheet_directory_uri() . '/style.css', $cache_buster, 'all'  );
  wp_enqueue_script( 'my-scripts', get_stylesheet_directory_uri() . '/scripts.js', array(), $cache_buster, true );
  wp_enqueue_style( 'childstyle' );

}
add_action( 'wp_enqueue_scripts', 'my_custom_files', 11);
Categories
Blog Code Snippets PHP

Send E-mail with Attachment using PHP

Here’s a perfectly working snippet of PHP code which will send an e-mail with an attachment (of any file type).

This code has been updated to disable jumbled/garbage/corruption which showed up on gmail (while it was fine on Outlook).

//File settings
$fileatt = "../uploads/myLovelyFile.pdf";
$fileatttype = "application/octet-stream"; //Octet-stream is a file type to allow all types of files
$fileattname = "myLovelyFile";

//Read file contents
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);

//Prepare file contents for e-mail
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$data = chunk_split(base64_encode($data));

$subject = "My Lovely Subject";

$mainMessage = "Hello,"
. "

This is my lovely message."
. "
Please see the attached file."
. "

Best Regards,"
. "
Kim";

$from = "Sandy Sender ";

$to = "Randy Recipient ";

$headers = "From: $from" . "\r\n";
$headers .= 'Reply-To: dispatcher@sender.com' . "\r\n"; //Optional
$headers .= "BCC: barbara@blindcopy.com\r\n"; //Optional

$headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"\n";
$headers .= "Importance: High\n"; //Optional
$message = "This is a multi-part message in MIME format.\n\n" . "–{$mime_boundary}\n"
. "Content-Type: text/html; charset=\"iso-8859-1\n"
. "Content-Transfer-Encoding: 7bit\n\n" . $mainMessage . "\n\n";

//Attach file to e-mail
$message .= "–{$mime_boundary}\n"
. "Content-Type: {$fileatttype};\n" . " name=\"{$fileattname}\"\n"
. "Content-Disposition: attachment;\n" . " filename=\"{$fileattname}\"\n"
. "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n" . "-{$mime_boundary}-\n";

// Send the email
mail($to, $subject, $message, $headers);

 

Categories
Blog Code Snippets PHP Wordpress

Add a new widget area to a WordPress theme

If you are familiar with WordPress themes then you know that a lot of themes have a widgetized sidebar. This means that you can add, remove, and re-order widgets on your WordPress website by using the “widget” section of your WordPress dashboard.

Having a widgetized sidebar is very useful, but you may want to widgetize other parts of your WordPress theme as well. This is very easy to do, and once your theme is modified it will be simple for you, or the WordPress administrator, to swap widgets in and out of different parts of the website.

Step 1: Add code to theme
The first step is to add the following line of code to the part of your theme that you want to widgetize. Be sure to change “Name of Widgetized Area” to a name that makes sense for you. You will need to do this with a code editor and then upload the file via a FTP client.

<?php
if ( is_active_sidebar( 'custom-header-widget' ) ) : ?>
    <div id="header-widget-area" class="chw-widget-area widget-area" role="complementary">
    <?php dynamic_sidebar( 'custom-header-widget' ); ?>
    </div>
    
<?php endif; ?>

Step 2: Edit functions.php
In your WordPress theme folder, there should be a functions.php file. If there isn’t, just make a new file and name it “functions.php”.

In the functions.php file, add the following code:

function wpb_widgets_init() {
    register_sidebar( array(
        'name'          => 'Custom Header Widget Area',
        'id'            => 'custom-header-widget',
        'before_widget' => '<div class="chw-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="chw-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'wpb_widgets_init' );

The code above should be wrapped in PHP open and close(<?php and ?>, respectively) tags. If you already have a functions.php file those tags will already be there. If you created one yourself you will have to add them.

Make sure to change the name of the function (in this case it is “Name of Widgetized Area”) so that it matches the name you gave it in step 1.

The ‘before_widget’ and ‘after_widget’ parameters allow you to specify what code you would like to put before and after each widget. In this case I put a div with an class for styling purposes.

The ‘before_title’ and ‘after_title’ parameters allow you to wrap the widget titles in code. In this case I wrapped the title in <h3> and </h3> tags respectively.

Step 3: Adding Widgets
Once you have successfully added the widgetized area, you can start adding widgets to your WordPress site. To do this, log into your WordPress dashboard, then click on Widgets in the Appearance dropdown on the left side.

You should now see the “Name of Widgetized Area” section on the right side of your screen.

Now just click and drag widgets into the box just like your sidebar!