Facebook Pixel implementation: some references.

Implementation

Implementation – Facebook Pixel

Cookie consent and GDPR

If you plan to serve European Union you will need to implement GDPR.

General Data Protection Regulation (GDPR) | Facebook for Business

Which means you will need to ask for user consent before tracking their activity on your website that involves personal data. Fortunately Facebook offers an API to pause Pixel from firing and fires once consent is granted:

fbq('consent', 'revoke');
fbq('consent', 'grant');

General Data Protection Regulation – Facebook Pixel

You can also use a tag manager for that purpose.

Tracking Events

Facebook Pixel API offers a wide range of standard events to track.

Examples:

fbq('track', 'Purchase', {currency: "USD", value: 30.00});
fbq('track', 'AddToCart', {currency: "USD", value: 30.00});
fbq('track', 'PageView');

You will find the complete list of standard event here Reference – Facebook Pixel.

Custom Events

fbq('trackCustom', 'ShareDiscount', {promotion: 'share_discount_10%'});

Conversion Tracking – Facebook Pixel

Parameters and Object properties

In the examples above you may have notice that some code got additional information beside the event name.

{currency: "USD", value: 30.00}
{promotion: 'share_discount_10%'}

Those are optional parameters written as JSON-formatted objects and allow to include additional information to your events.

We have seen value parameters and promotion but you might want to add the category where the event took place

{content_category: "name_of_category"}

You can just as easily create custom parameters.

{custom_parameters: "some_value"}

or even more complex objects:

{contents: [
      {
        id: '301',
        quantity: 1
      },
      {
        id: '401',
        quantity: 2
      }]}

You will find more information on the link above where parameters are treated, plus you have some example above.

Migrating a static site to WordPress CMS

In this article we will consider that you have already finalize your site on WordPress on a development server, backed up your production site and that you are ready to do the transfer. We will simply mention that once you have finalized you site on the development site don’t forget to redirect your page through .htaccess.

Redirections

Your .htaccess will look like that:

<IfModule mod_rewrite.c>
RewriteEngine On

</IfModule>

# BEGIN WordPress
# Rivit, jotka ovat "BEGIN WordPress" ja "END WordPress" välissä on luotu dynaamisesti ja niitä tulee muokata vain WordPressin filttereillä. Kaikki manuaaliset muutokset riveihin tullaan yliajamaan.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /

#My redirect

RewriteRule ^some_url.html$ https://www.example.com/some/new_url/ [L,R=301,NC]

#End redirect

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
#BEGIN CUSTOM

Note that the simple 301 redirect:

 Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html Redirect 301 /oldpage2.html http://www.yoursite.com/folder/

as described here, won’t work as is in the WordPress .htaccess, hence the use of the previous method. Not that the URL being redirected does not use the domain name.

If you have to redirect files and folders that are hosted in a subdomain, make sure to modify the .htaccess accordingly in the affected directory.

We also recommend that you redirect your image to not lose any image traffic.

Moving WordPress

WordPress.org has a good documentation about moving wordpress:

In our case study, the paragraph about changing domain name and URLs is particularly of interest to us.

One thing that is not explicitly mentioned is that the column guid in the wp_posts column in the database won’t change and still refer to your development server. To solve this you might think of running an SQL command to update the gui to your new domain name:

UPDATE wp_posts SET guid = REPLACE(guid, "old[DOT]com",  "new[DOT]com");

but this operation is not recommended due to data serialization issue. I tested one of the recommended plugin in the article (better search replace) and it worked well.

Uninstall problematic plugins before migration

Note that some plugins might cause issue during the migration because they have hardcoded your previous domain (the development one). In that case you might want to uninstall them before migration. Some plugins doesn’t do proper garbage management and you might need to do some manual cleaning.

In my case, I had to uninstall Wordfence and manually clean the database and some files and folders. You will find all required information on Wordfence site. There is an advance uninstall option that is suppose to do that for you, but I was not aware of it at the time. It seems to be a separate plugin:

YITH WooCommerce Wishlist caused also issue by requiring a file that was not there (and also missing in the dev site but without causing issue). So you can also just uninstall it before backing up for migration and reinstall it once migration is complete. In my case I commented out the incriminated line which allow me to access the dashboard and updated the plugin, which solved the issue.

Minimizing down time

If your site have a large amount of pictures and you want to minimize downtime, we recommend that you upload your picture before hand on the production site ahead of the migration.

If you have followed the moving WordPress tutorial, you have done a backup of your development site and its database, changed the URLs in wp settings – general, which leads to a 404, backup your dev site and its database after the change you can upload the following folder to your production site, without interrupting production: wp-admin, wp-content, wp-includes.

Make sure you have php version compatible with wordpress on your production site.

Create a database to upload the database of your dev site (the one you did after changing the domain in the settings). Note the user name, use password, database name and host as you will need it later.

Finalize migration

Once you have finished transferring your pictures and the WordPress folders and imported your database table in the production database, you are ready to finalize the migration. Delete the folders related to the previous version of your site and upload all the WordPress files that lies at the root of your dev site.

robots.txt

Check that your site is discoverable in WP Reading Settings and double check the robots.txt and do your redirect as indicated at the beginning of the article.

Google search console

Make sure to update your site map URL in case it differs from the version prior to migration.

Analytics

And finally add your analytics tracking code to your new site.

Profit.

namespaces in PHP and autoloader

References

About namespaces:

About autoloading:

About SPL:

When the autoloader is located in the folder holding your classes, then use the relative namespace for the class. For instance, if all your classes are in a Vendor folder and you want to load the User class with the path Vendor/Model/user.php, then the classname to load is ‘Model\User’. In the example below the myautoloader.php file is held in the Vendor directory.

namespace Vendor;

class MyAutoloader
{
public static function autoload(){

    spl_autoload('Model\User');

}
}
spl_autoload_register('Classes\MyAutoloader::autoload');


$conn= new Connect\Connect;

Now we would need to recursively fetch the classes in the directory to load them automatically.

File System Iterator

References:

$pathTop = __DIR__; //pathTop because we will recursively loop through directory starting from the current file directory at the top most category. Check get_url snippet to change that or use substr()

$directory = new RecursiveDirectoryIterator($pathTop, RecursiveDirectoryIterator::SKIP_DOTS); // this return an iterator sarting in the current file directory
var_dump($directory);
echo $directory;

$fileIterator = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::LEAVES_ONLY);

var_dump($fileIterator);
	
foreach($fileIterator as $file){
	echo $file.'<br>';
	$path_array=explode('\\',$file);
	echo $path_array[count($path_array)-2];
	echo '<br>';
	echo $path_array[count($path_array)-1];
}

Get a form input field value with javascript

You can use document.getElementById("input_field_id"); or you can use:

var form=document.forms["form_name"];
var input_value= form["input_field_id"].value;

Note that the typeof(input_value) will be string even if the type of the input field is “number”.

So even if you enter an integer in the field Number.isInteger(input_value) will return false and typeof(input_value) will return string.

Incorrect integer value: ” for column …

Error message: Incorrect integer value: ” for column

Error description: the error occurs when inserting an empty value in a column.

Solution: This behavior is normal and shows that your sql-mod is set to strict. To change that access your server and look for the my.ini file. Locate the sql-mode line and set it as sql-mod=””

Set a dedicated 404 page in .htaccess

In the redirect section of your .htaccess file just add the following line:

ErrorDocument 404 https://example.com/404/

Replace the url by the actual url of your dedicated 404 page as you would do for any other redirect.

Now all what’s left to do is to create the page in your CMS back end (or code one in html if you are running a static site).

Get the time it takes to run a given function in PHP

To get the time in microsecond you will need to use microtime() instead of time().

You will need microtime() to return a float so set $getAsFloat to true like this:

microtime(true);

Most of the function are really fast so to get something measurable you might need to run them several thousands time within a loop:

$start=microtime(true);
for( $i=0;$i<100000;$i++){
  //the function you want to test
}
$end=microtime(true)
$total_runtime=$end-$start;

You might want to use this method to compare two functions and verify which one is the fastest. You can then compare the time it took to run each of your function and pick the smallest one.

Get the category archive name and description in a wordpress theme

If you need to access your achive title and or description, you can the code below. I used it to take the description as meta description. A better policy would be to write a custom metadesciption. But that’s a quick fix while you are working on a better solution.

    $title=get_the_archive_title();
    echo(explode('<',explode('>',$title)[1])[0]);
    if(get_the_archive_description()){
	echo '<meta name="description" content="'.preg_replace('/\<.*\>/',' ',get_the_archive_description()).'">';
    }

Change number of product displayed in woocommerce

Add this code in you theme functions.php. Make a child theme if you are using someone else theme to avoid your changes being overwritten during the next update.

/**
 * Change number of products that are displayed per page (shop page)
 */
add_filter( 'loop_shop_per_page', 'new_loop_shop_per_page', 20 );

function new_loop_shop_per_page( $cols ) {
  // $cols contains the current number of products per page based on the value stored on Options -> Reading
  // Return the number of products you wanna show per page.
  $cols = 9; //Enter the number of products you want per page here
  return $cols;
}

Add open graph meta to your virtuemart and joomla template.

Facebook usually does a good job at picking up all the required information from your web page but there is some instance where you might want to have better control on what image is displayed as thumbnails or have a customize description for Facebook sharing. In that case you will need to use facebook open graph.

List of basic properties: https://ogp.me/

  • og:title
  • og:type
  • og:image
  • og:url

The required meta properties for open graph are the following according to facebook Sharing Debugger :

  • og:url
  • og:type
  • og:title
  • og:image
  • og:description
  • fb:app_id

og:url

We will need to get the URL of the page currently displayed. Joomla doc gives us the solution here: https://docs.joomla.org/URLs_in_Joomla

In index.php simply add:

use Joomla\CMS\Uri\Uri;
$uri = Uri::getInstance();
$url = $uri->toString();

And within your <head> element:

<meta property="og:url" content="<?php echo $url; ?>"/> 

og:title

To get the current page title, Joomla documentation gives us again the answer: https://docs.joomla.org/Add_Static_Text_In_Title_Of_Page

<?php
$title = $this->getTitle();
?>

and within the <head> element:

<meta property="og:title content="<?php echo $title; ?>"/>

og:image

Automated this task will be a bit more challenging as the URL of the image will change from page to page. For instance, images from home page, post and product and category pages won’t be called the same so you have to check the type of page you are displaying to call the right type of image.

For the home page, you can set the og:image content manually. You will need to check first if the user is currently viewing the front page:

https://docs.joomla.org/How_to_determine_if_the_user_is_viewing_the_front_page

<?php 
$app = JFactory::getApplication(); 
$menu = $app->getMenu(); 
$lang = JFactory::getLanguage(); 
if ($menu->getActive() == $menu->getDefault($lang->getTag())) 
 { 
  echo 'This is the front page'; 
 } 
else 
 { 
  echo 'Accueil'; 
 } 
?>

It seems there is a bug in Facebook Open Graph for the image property in website requiring https. We speak about it here. On my side the issue is only present in messenger. Sharing a page as a post is working as expected.

og:type

The default is ‘website’ but there exists a ‘product’ type that can be of interest in product pages

<meta property="type" content="website" />