Categories
Code Snippets Javascript JQuery SquareSpace Wordpress

SquareSpace | WordPress | CMS Friendly | Scroll to Top Button

In this tutorial, we’ll be adding a Scroll to Top button to the website. These steps will work for SquareSpace, WordPress and any other CMS.

See it in action here: https://billmuirhead.com

First, let’s add the button to the body of the page.

Get the identifier on your header element, it may be on the <nav> element on something similar which lives on the top of each page.

In this case we’re using #site-header where we have a div with id = site-header.

Be sure to add the code below to the body element in such a way that it will show on each page such as the header or footer.

<a class="to-the-top" href="#site-header">
    <span class="to-the-top-long">
    To the top <span class="arrow" aria-hidden="true">ā†‘</span>
    </span><!-- .to-the-top-long -->
    <span class="to-the-top-short">
        Up <span class="arrow" aria-hidden="true">ā†‘</span>
    </span><!-- .to-the-top-short -->
</a>

Next, let’s add the javascript/ Jquery to add the scroll to top functionality to the button. It will the button when we’re already at the top!

First, add the following Jquery script tag to the Footer section to make sure Jquery is enabled:

<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>

Following that, add the Scroll to Top javascript code also to the Footer section immediately after the Jquery script above.

jQuery( document ).ready(function() {
    
            
    jQuery(window).bind('scroll', function() {
            
            wrap = jQuery('body');
            scrollTop = jQuery(window).scrollTop();
        
            distance = 50;
            console.log("slide height!");
                                     
            if (scrollTop > distance)	{
                wrap.addClass("fixed");
                jQuery( ".to-the-top" ).show();
            } else {
                wrap.removeClass("fixed");
                jQuery( ".to-the-top" ).hide();
            }		
        
    });	
    
    
    jQuery( ".to-the-top" ).click(function() {
        
        document.body.scrollTop = 0; // For Safari
  		document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
        
    });
    
});

Video explanation for implementing on SquareSpace :

Categories
Code Snippets CSS Javascript JQuery SquareSpace

SquareSpace | How to Add an (FAQ) Accordian

HTML====
<button class="accordian">
  Section 1
</button>
<div class="panel">
  <p>
    Lorem ipsum....
  </p>  
</div>
<button class="accordian">
  Section 2
</button>
<div class="panel">
  <p>
    Lorem ipsum....
  </p>  
</div>
<button class="accordian">
  Section 3
</button>
<div class="panel">
  <p>
    Lorem ipsum....
  </p>  
</div>

CSS====
<style>
  
  .accordian {
           background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        text-align: left;
        border: none;
        outline: none;
        transition: 0.4s;
  }
  
  .panel {
       padding: 0 18px;
    background-color: white;
    display: none;
    overflow: hidden;
  }
  
  .active, .accordian:hover {
           background-color: #ccc; 
  }
  
  .accordian:after {
           content: '\02795';
        font-size: 13px;
        color: #777;
        float: right;
        margin-left: 5px;
  }
  
  .accordian.active:after {
           content: '\02796'; 
  }

</style>

Javascript====
<script>
    var acc = document.getElementsByClassName("accordian");
      var i;
  
      for (i = 0; i < acc.length; i++) {
         acc[i].addEventListener("click", function() {
              this.classList.toggle("active");
              var panel = this.nextElementSibling;
          
              if(panel.style.display === "block") {
                 panel.style.display = "none"; 
            }
              else {
                 panel.style.display = "block"; 
            }
        });
    }

</script>

 

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
CSS Wordpress

Remove image zoom feature from woocommerce products

function remove_image_zoom_support() {
remove_theme_support( 'wc-product-gallery-zoom' );
}
add_action( 'wp', 'remove_image_zoom_support', 100 );

 

Categories
Blog Code Snippets Wordpress

Remove the word “Archives” from the Archive Page Title

Add this to functions.php

function grd_custom_archive_title( $title ) {
// Remove any HTML, words, digits, and spaces before the title.
return preg_replace( '#^[\w\d\s]+:\s*#', '', strip_tags( $title ) );
}
add_filter( 'get_the_archive_title', 'grd_custom_archive_title' );

Or use:

function override_page_title() {
return false;
}
add_filter('woocommerce_show_page_title', 'override_page_title');

 

Categories
Code Snippets CSS Javascript JQuery

Add a Class to your Header on Scroll

jQuery( document ).ready(function() {
            
    jQuery(window).bind('scroll', function() {
            
            wrap = jQuery('body');
            scrollTop = jQuery(window).scrollTop();
        
            distance = 50;
                                 
            if (scrollTop > distance)	{
                wrap.addClass("fixed");
            } else {
                wrap.removeClass("fixed");
            }		
        
    });

});

 

Categories
Code Snippets CSS Javascript

Load CSS File Dynamically with Javascript

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'https://kimberleydurrant.com/test.css';
    link.media = 'all';
    head.appendChild(link);
}

 

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
Javascript JQuery

Trigger Child Link when Parent is Clicked

Use the code below. Simply change “.parent” to match the parent’s class.

jQuery('.parent').click(function() {

    window.location = jQuery(this).find("a").first().attr("href");

});

 
Also, add a hover effect to the parent element using css so that users know its clickable.

.parent:hover {
    cursor: pointer;
}
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 )) {