The latest update to PHP7 is here… 7.2.0

This month PHP released the latest update PHP7.2.0. While PHP 7.2 is an improvement, it is not groundbreaking as the jump from PHP5.6 to PHP7.0. However the biggest change, having encryption as part of the standard library in PHP, is very exciting. As PHP7 evolves and developers get more interesting tools to work with there are more and more reasons for dumping PHP5 and embracing the change.

Amongst the security updates there are a few cool new features and a couple of significant deprecations. Carlo Daniele has compiled a list here.

Running web applications on PHP7.2.0

Magento2 & PHP7.2.0

If you’re running Magento2 now might not be the best time to upgrade your PHP installation. It is important to note that both each() and mcrypt() have been removed from PHP 7.2. So stick with PHP 7.1, it doesn’t reach its end of life until 2019. Full list M2 requirements from Magento.

Magento 1 & PHP7

Out-of-the-box Magento 1.X installs are not designed to run on PHP7 at all. If you really need to run Magento 1.X on PHP7 Inchoo have created an our open-source compatibility extension for Magento and PHP 7 with impressive speed improvements. Details here

WordPress & PHP7.2

As you’d expect as long as your WordPress install is up to date it’ll run fine.

PHP: glob

glob($string);

Return an array of pathnames matching a specific pattern.

// Find all CSV files in the /home/var/imports/ directory 
glob("/home/var/imports/hello-*.csv");
  • /home/var/imports/hello-world.csv – Returned
  • /home/var/imports/hell-world.csv – Not returned
  • /home/var/imports/hello-.csv – Returned.

Magento Code: Check an import directory for new product CSVs and process using a Magmi profile

This script will first scan the var/import directory for all CSV files starting “import-” using the glob() function in PHP. It will return an array of any files which match the query in the directory including the file path from root.

The $file_parts will be used later when we need just the file name.

$cmd is the executable shell command we will be using to load Magmi, set the profile, mode and chosen file.

The shell_exec() function runs the command and will return any output to the $output variable, this can be expanded to check for a successful import. The script below will carry on regardless of import status.

Once the import is complete we take the CSV and copy it into an archive folder, just in case we want to reuse it. The original file is then deleted from the var/import folder using unlink()

This script can then either be run manually, or set-up as a scheduled task using Cron.

// Find all CSV files in import directory
$files = glob('/home/admin/public_html/var/import/import*.csv');

// For each of the files found 
foreach ($files as $file):

   // Explode for teh the file name in 6th position of the array
   $file_parts = explode("/",$file);

   // Set-up the command 
   $cmd = 'php /home/admin/public_html/magmi/cli/magmi.cli.php -profile=default -mode=create -CSV:filename="'.$file.'"';

   // Execute the comamnd 
   $output = shell_exec($cmd);

   // Copy the executed script into an archive folder
   if ( copy($file,'/home/admin/public_html/var/import/archive/'.$file_parts[6]) ):
      // Delete the original
      unlink($file);
   endif;

endforeach;

PHP: header

header($string);

Used to send a raw HTTP header, often used for page redirects.
Must be called before any other output is sent.

// Redirect the request to https://keithgreer.uk
header("Location: https://keithgreer.uk");
// Send an error code to the browser, for example a 404
header("HTTP/1.0 404 Not Found");

PHP: str_replace

str_replace($search,$replace,$subject)

All instances of $search are replaced with $replace in $subject.

// Will print to screen: "Why is the sky blue?". 
echo str_replace("red","blue","Why is the sky red?")

Magento Code: Include currency switcher in the header or footer with Foundation mark-up

It is easy to set-up multi-currencies in Magento. This code  allows you to quickly include a currency drop down or link to  the header or footer of your Magento store. Before you begin make sure you have enabled more than one currency  as this example won’t work without at least one additional currency alongside your base currency.

Set-up the following code in your theme directory /app/design/frontend/package/theme/template/currency/currency.phtml. I’ve included code for both a drop down select box, or inline list of hyperlinks.

Continue reading Magento Code: Include currency switcher in the header or footer with Foundation mark-up

Magento Code: Add a drop down attribute and display it on the product page in custom HTML

Magento makes it really easy to expand the usual product attributes through the Admin Panel. While these can be added to the product page in the standard attribute list table, you may want your attribute to appear differently or use it for another feature. This post explains how.

In this example we’ll be adding an attribute to tell the customer how long they might have to wait on a product to arrive.

Continue reading Magento Code: Add a drop down attribute and display it on the product page in custom HTML

Magento Issue: Unable to sort configurable product attribute drop down options

Having encountered this issue a couple of times I though it was time to make a note. This is a fix for an issue in Magento 1.9 whereby the order specified for option attributes in the admin panel are not being applied on the front end.

Jonathon Byrd at Merchant Protocol has published this fix which overrides the core Configurable Attribute Collection class with an updated one which properly sorts the attribute options by the sort value in the Admin panel.

» [Solved] Sort Configurable Product Attribute Options and Dropdowns

Jonathon’s fix works perfectly. I’ve implemented it alongside a simple product pricing module for configurable products also without issue.

WordPress Code: Completely disable comments using functions.php

The code below will completely disable any commenting and trackback features in WordPress. This code won’t turn off any “This post has X comments” or front-end code that displays comments that may be in your theme. Instead it removes the ability for comments to be added/stored against posts.

It is in response to the usual issue whereby you think comments have been completely disabled only to get a notification that there is a new comments waiting moderation.

Simply copy and paste into your functions.php file in your template.

// First, this will disable support for comments and trackbacks in post types
function df_disable_comments_post_types_support() {
   $post_types = get_post_types();
   foreach ($post_types as $post_type) {
      if(post_type_supports($post_type, 'comments')) {
         remove_post_type_support($post_type, 'comments');
         remove_post_type_support($post_type, 'trackbacks');
      }
   }
}
add_action('admin_init', 'df_disable_comments_post_types_support');

// Then close any comments open comments on the front-end just in case
function df_disable_comments_status() {
   return false;
}
add_filter('comments_open', 'df_disable_comments_status', 20, 2);
add_filter('pings_open', 'df_disable_comments_status', 20, 2);

// Finally, hide any existing comments that are on the site. 
function df_disable_comments_hide_existing_comments($comments) {
   $comments = array();
   return $comments;
}
add_filter('comments_array', 'df_disable_comments_hide_existing_comments', 10, 2);

WordPress developer

in Belfast, Northern Ireland

I’ve been developing WordPress websites for 10 years and am always looking for the next exciting project from personal blog, community portal or business website. Why not get in touch to see if I can help you with yours.

Contact me today!

How to use PHP to submit a cURL request with HTTP Post data

Straight forward script to POST an array of fields to a given URL.

// First, set the URL you want to POST the data to
$url = 'http://domain.com/script/';

// Specify the POST data
$fields = array(
  'field1' => "Value 1",
  'field2' => "Value Two",
  'field3' =>  "Value 3"
);


// Next, erge the array data into a single sting
foreach ($fields as $key => $value) { $fields_string .= $key . '=' . $value . '&'; }
$fields_string = "";
rtrim($fields_string, '&');

// Open a CURL connection
$ch = curl_init();

// Set the CURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

// Fire!
$result = htmlspecialchars_decode(curl_exec($ch));

// Close your connection
curl_close($ch);

And that’s it. The $result variable will contain the response from the request. Depending how this is provided it might be plain text, JSON or pretty much anything else imaginable (over HTTP).

If it is a JSON string it can be converted to an object as follows:

$decode = json_decode($result);

Where $decode is a PHP object.

Magento Code: Bulk add a new product attribute to all store attribute sets

This little script is an excellent time saver for adding a new attribute to all of the attribute sets configured in your Magento store.

There are a few attributes to update:

  • Replace **ATTRIBUTE CODE** with the code of the attribute you wish to add.
  • Replace **ATTRIBUTE GROUP NAME** with the group name
  • Replace **SORT ORDER** with sort order you want it to display, as you’d expect.

Upload the script to the Magento root folder and hit with your browser.

PHP: Use WordPress blog tags to find related posts

A simple script that can be used to pull related-type posts for a WordPress blog post. The related aspect is based on the fist tag assigned to the post. The script will return at most 5 other posts from the site that also include the first tag.

<?php

$tags = wp_get_post_tags($post->ID);

if ($tags) {
    
    $first_tag = $tags[0]->term_id;
    
    $select = array(
       'tag__in'          => array($tags[0]->term_id),
       'post__not_in'     => array($post->ID),
       'posts_per_page'   => 5,
       'caller_get_posts' => 1
    );
    
    $tag = get_tag($first_tag);
   
    $tag_query = new WP_Query($select);
   
    if( $tag_query->have_posts() ) {
        echo "<ul>";
        while ($tag_query->have_posts()) : $tag_query->the_post(); ?>
            <li>
                <a href="<?php the_permalink() ?>">
                   <?php the_title(); ?>
                </a>
            </li>

        <?php endwhile;
        echo "</ul>";
    }
    
    wp_reset_query();
}

?>

WordPress developer

in Belfast, Northern Ireland

I’ve been developing WordPress websites for 10 years and am always looking for the next exciting project from personal blog, community portal or business website. Why not get in touch to see if I can help you with yours.

Contact me today!

Import Values to Dropdown/Multiple Select Attributes

Sometime when you need to deal with import of lots of values for a multiple select/drop down attribute. Then manual data entry is not very convenient. The code below will allow you to put all your values into a single text file and import in seconds. First you will need to upload the source code below into a new file manufacturer_import.php in the Magento root directory.

Continue reading Import Values to Dropdown/Multiple Select Attributes