WordPress Editor is Missing Tabs

I found my site was missing the “Visual” and “Text” tabs along with several other options including the “Kitchen Sink” option that adds the entire second row of menu options to the WYSIWYG editor! So, I was lost without these options and the fix was very difficult to figure out, so I’m going to share it in case someone else has this happen to them.

First off, let me just say that this may not be the solution for you. While searching for the solution, I saw there were several other issues that can cause this, so I’ll go over some of the easy and more common fixes first for you just in case. If the first two solutions don’t work, scroll down to my “The Tricky Fix” section below and give that one a try because that’s the one that got it working for me.

The Easy Fix:

The easy fix is to simply navigate to wp-admin and go to “Users”/”Your Profile” and at the top of your profile admin page you’ll see the “Visual Editor” option with a checkbox that reads: “Disable the visual editor when writing”. All you have to do is make sure this box is NOT CHECKED and then scroll to the bottom of the page and click on the update button to save your settings. Even if it was not checked to begin with, try checking, saving and then uncheck it and save it again and test the post/page editor again and sometimes this alone will make it work, but if it didn’t, keep reading!

The Difficult Fix:

The more difficult but probably second most common fix involves reinstalling or updating WordPress. If that doesn’t work, try disabling plugins one at a time to see which one may be causing the issue. Hopefully one of these first two fixes worked for you because those are the most common ones, however keep reading if you have yet to find a solution that enables your visual editor and missing editor tabs in WordPress. There’s one much trickier solution that is very hard to fine, but rather easy to implement….

The Tricky Fix:

Now for the tricky fix. This fix saved my day! If I hadn’t found it I would have spent all day trying different tricks to fix my Visual Editor and missing buttons issue for my WordPress blog, Jafty.com/blog. It has to do with missing headers and is related to a server issue that I admittedly do not fully understand. All I know is that this fix works if your server has this particular issue as mine did. All you have to do is add a few lines of PHP code to any active plugin or to your theme’s functions.php file. If you are not a plugin developer who happens to be making a plugin at this time, I would add it to my functions.php file. Here is the code:

function richedit_wp_cloudfront () {
add_filter(‘user_can_richedit’,’__return_true’);
}

add_action( ‘init’, ‘richedit_wp_cloudfront’, 9 );

Simply add that to the top of your functions.php file, save it and upload it to your server and refresh the page with the editor on it and it should now work. Mine did. If this doesn’t work, then unfortunately you must have a different sort of issue than I did. I have read online that Amazon servers can have this problem, although it happened to me on a Linode server. Good Luck!

How to Stop WordPress Functions from Running More than Once

I’m going to share what I learned yesterday because it took me about five hours to figure this out and I hope to save other people and myself from having to spend so much time figuring this out in the future. I was working on a plugin for a client that had to fire a function using the init WordPress hook, something done quite often in plugin development. The problem was that this function was running more than one time each time a page loaded. In a perfect world, init should only fire one time per page load, but in real life, it often fires more than once. I’ll get into some reasons for this later, but for now just understand that the problem was related to a PHP function running more than once per page load and I only wanted it to run one time per page load.

The WordPress Init Hook

The WordPress init hook fires after WordPress has finished loading but before any headers are sent. It is very often NOT the best WordPress hook to tie a function too, in fact it should be used quite sparingly! However, should you find a need to use it, this post should help you some I hope. You should only use the init hook if you want something to happen every time any page is loaded. By any page, I mean any admin page or front end page including error pages and everything, so be careful how you use it!

The Main Issue With Init Hook

In my opinion the main issue with using the init hook to call a function in WordPress is that it can be rather unpredictable depending on the state of your WordPress site. For example, the most common issue that can cause the init hook to fire more than once per page load is missing images and missing scripts that are part of the page being loaded but that WordPress can’t find. Every time a page’s image is missing or a script that is linked to the page is missing, a 404 error occurs which in turn fires init yet again. That means if you hook a function into init that opens a pop up window that says “Hello World!”, and the page you open in a browser is missing the header image, then it causes that pop up window to open two times. Now if you happen to be also missing a linked to css file, it could fire even a third time etc…..needless to say, it could be very inconvenient for you as a coder and the end user who has to close all of those nasty pop ups you inadvertently subjected them too…

The Solution

Now, lets say you’ve read to hear and you still want to use the init function or you have no other choice in the matter, then you can do what I did. First I tried several other methods recommended on the internet to stop my function from running more than once. I will list some of those methods here just so you don’t waste your time on them like I did. Please note that some of the methods may work for you if the situation is a little different, but if you are trying to stop a function from running more than once at a time and that function is triggered by the init WordPress hook, then none of the following are likely go work for you:

What Did NOT Work

  1. First I tried simply writing the time to the database ea. time the function ran and also made it so the function read in the time and if it was less than a minute ago, it wouldn’t run the function again in theory. In practice, this doesn’t work! Trust me. Not for this situation at least.
  2. Then I tried using something new to me, semaphore. Semaphores are PHP protected variables used to control access to some resource. They are developed by Dijkstra. I think the reason semaphores didn’t work to stop a function from running more than once was because often times the init hook will fire twice within a hundredth of a second making it almost simultaneious and that doesn’t give the semephore time to work. Don’t expect semaphores to work if you are using the init function and you want to stop a function from firing more than once, but you can learn more about Semaphores here: http://www.re-cycledair.com/php-dark-arts-semaphores. They are interesting, just not for this scenario.
  3. I also tried various methods of saving to the options table using a built-in WP function such as update_option and similar, but everything was too slow to catch the nearly simultaneous firing of the init hook that seem to occur often in WordPress.
  4. The main reason for the init hook firing multiple times per page load to begin with is due to missing images and files as I explained above, so the next thing I tried was to simply clean up the site. If you have a small site, fixing all broken links, images and missing files will probably work for you, but if you have a site like the one I’m working on, forget it! I tried, but quickly found out that it would be a multiple day project to go this route, so I moved on to the next solution. This one however may work for some of you. The way I would go about it is to use Firefox and inspect the page using the web console with the network requests visible. You have to refresh the page after you set them to visible to see all of the network requests. Then simply look for 404 errors and it should tell you all of them for that particular page. You’ll have to do this for every page in the site is why I don’t recommend this solution for larger sites.

What Finally Worked for Me

Now, what worked for me was a combination of things I tried above in a way. I’ll try to keep it short and get to the solution instead of how I came to it because that is a never ending story! Here is some example code that I simplified because this was part of a much more complex and copyright protected solution for a client. This snippet will show you how to stop functions fired by init from running more than one time in the same minute(or whatever interval you set):

<?php
/*
This is example code for how to make a function triggered by the WordPress Init hook only run once per page load and only once per minute or other time interval as set in the code.
*/

//hook a function handler function to init instead of the main function that does the work:
add_action(‘init’, ‘function_handler’, 10, 3);
function function_handler(){
//start out with a random pause from 1 to 5 seconds:
$rn = rand(1000000, 5000000);
log_debug(“Random time was $rn\n”,”a.log”);
usleep($rn);//1000000 is 1sec and 250000 is 1/4 sec etc. 100000 is about 1/10 of a sec.

//get last time the import function was ran from time.txt
$cdir = plugin_dir_path(__FILE__);//get dir of current file with trailing slash
$tFile = $cdir.’time.txt’;
$ftime = “”;//set default value for ftime:
if($file = fopen($tFile, “r”)){
//Output line at a time until end is reached:
while(!feof($file)) {
$ftime = fgets($file);
}
fclose($file);
//log time fetched from time.txt
log_debug(“Time retrieved from time.txt: $ftime\n”,”a.log”);
//log each time this function is called:
}else{
log_debug(“failed to read time.txt time\n”,”a.log”);
}

$lasttime = new DateTime($ftime);//turn time found into a valid DateTime obj.
$dt = new DateTime(“now”);//put the current time into valid DateTime obj.

$dtf = $dt->format(‘Y-m-d H:i:s’);//format $dt or current time to display it
log_debug(“Current time: $dtf\n”,”a.log”);

$lasttimef = $lasttime->format(‘Y-m-d H:i:s’);//format time found to display it
log_debug(“last time ran(according to time.txt): $lasttimef\n”,”a.log”);

//get difference between $dt and lasttime:
$dteDiff = $lasttime->diff($dt);
//format the time difference in a human readable format:
$time_diff = $dteDiff->format(“%H:%I:%S”);
log_debug(“Time since import function last ran: $time_diff\n”,”a.log”);
//see if $time_diff is more than a minute and if not, stop function now!
$comparetime = strtotime(“00:01:00”);//set to max time allowed between function calls!
$timediff = strtotime($time_diff);
if($ftime == ” || $timediff > $comparetime){
//if no time stored yet or time diff is more than a minute, then continue…
log_debug(“ftime was blank or it has been more than a minute since last run so continuing to run import function next!\n”,”a.log”);
}else{//otherwise, kill operation of function because it hasn’t been enough time:
log_debug(“——NOT enough time since last run. import function stopped!\n”,”a.log”);
return;//stops execution of this function here!
}
//code past here only gets executed if it has been more than x minutes since last import
//store time in time.txt:
$fh = fopen($tFile, ‘w’) or die(“can’t open time.txt file to append, Please make sure your follow-hook folder and all files are owned by the www user(user www-data usually). To change ownership you have to access your server command line and issue the command: ‘chown -R www-data:www-data cutivate-crm’ while you are in the wp-content/plugins directory(cd /var/www/yoursite.com/public_html/wp-content/plugins). If problem persists, email developer, Ian L. at linian11@yahoo.com”);
fwrite($fh, $dtf);
fclose($fh);
//go ahead and run your import function now:
import_function();//this is the function that will only get run once!
}//End function_handler PHP function by Ian L. of Jafty.com

function import_function(){
log_debug(“***import_function has been triggered!***\n”,”a.log”);
}//end import_function that can only be ran once a min max.

//Custom function to write data to log file:
function log_debug($log,$filename=’a.log’){
$pdir = plugin_dir_path( __FILE__ );//gets the directory of current file with trailing slash whether inside plugin or not!
$myFile = $pdir.$filename;
$fh2 = fopen($myFile, ‘a’) or die(“Error – can’t open $filename to append…”);
fwrite($fh2, $log);
fclose($fh2);
}//End log_debug PHP function

?>

That’s my solution! Let me explain a little more. The above code is meant to go in a plugin file since this is a technique that should really only be used by plugin developers. It could also go into a theme’s functions.php file, but is less likely to be used there since it depends on other code and isn’t meant to be by itself really. In my case I had a function that imported users into a WordPress site as posts and it had to be done every x minutes, so I had the init hook call the function_handler function. That function_handler function is just to keep the import_function from being called more than one time per minute.

Before I had this set up I had the import_function being called from the WordPress init hook and inside the import_function I logged ea. time it ran to a log file and sometimes when a page was loaded, I would see lines like this in the log file:

Apr,23,2019 07:53:43 PM – check_import_queue function began….

Apr,23,2019 07:53:43 PM – check_import_queue function began….

…and somtimes I might get something like this:

Apr,23,2019 08:03:03 PM – check_import_queue function began….

Apr,23,2019 08:03:04 PM – check_import_queue function began….

…and other times there might be three of these lines or more and sometimes there was only one as it should be, but not often. So, as you can see, some were posting the exact same time and some were only a second apart, so I developed the above code to make them at least be a minute apart to keep my server from getting backed up with import calls. The import function itself was coded to prevent doubles(two of the same person) from being inserted into the post type, but WordPress is not able to catch doubles if the import function was fired within a second or less from the last time it was fired. Therefore without the above code, I would get hundreds of double posts even with code in place to stop it. It simply would not work without the code I wrote above.

The Random Pause

You probably noticed at the start of the code there is a random pause from 1 to 5 seconds. This keeps the function_handler function from writing more than one line to the time.txt file at a time and also will help give WordPress time to do what it has to do in the background as well. I’ve tried it without the pause and it doesn’t work.

Writing to a .txt File

The part of the code that writes the times the import_function was run to a .txt file named time.txt is also part of the trick that makes this work. I could find no other way to store the data fast enough for it to be ready by the next time the init hook fired. I tried storing it in a custom database table and in the WordPress options table, both methods failed. I also tried using a PHP semaphore as I mentioned above and that too failed in my case.

 

WordPress Post Link Not Working

If you’ve been using WordPress for a good length of time now, you have likely come across a time when you published a post and tried to visit the page and it gave you a 404 not found error, right? Of course I’m right or you probably wouldn’t be here reading this, so here are a couple common fixes you should try first when this happens.

Re-Save Permalinks

The first thing I always try is to simply go to wp-admin/settings/Permalinks and make sure the settings are correct and even if they are, save them again just by clicking the button at the bottom of the page even if you do not change a thing! This will often fix your problem, but not always.

Re-Name Your Post and Permalink

Sometimes simply giving your post a new name and changing the Permalink at the top of the page will resolve the problem as well. To do this, simply change the title by adding a word or two and then change the permalink right under the title by changing it to match the new title but make it all small letters and replace spaces with hyphens. One reason this might work is if you had accidentally used a reserved word for your title  or a title that exists for some other purpose in WordPress. When that happens it will simply ignore it and show you a 404 link instead usually. If you do not want to change your posts title, then you can probably get away with just changing the permalink right under the title, but you always have to change the permalink at least to be sure you’re not using a reserved word or link that is already in use somewhere else within WordPress.

 

 

Basic WP Cron Jobs

This is going to be a simple WP Cron tutorial that explains the basic use of WordPress cron, the wp_schedule_event function and it’s 3 built in intervals. I’ll write a more complex one soon that explains how to add your own intervals, but this is a good starting point:

Practical Code Example

<?php
//Add function to register daily function on WordPress init
add_action( ‘init’, ‘register_daily_cron’);

// Function which will register the daily event:
function register_daily_cron() {
    // Make sure event hasn’t been scheduled already:
    if(!wp_next_scheduled(‘daily_cron’)) {
        // Schedule the event
        wp_schedule_event(time(), ‘daily’, ‘daily_cron’);
    }
}

?>

Don’t Hard Code WP-Content Directory!

Plugin development tip of the day!
DO NOT HARD CODE wp-content Directory!

I made this mistake not realizing how many people change that directory as a security precaution.

Alternatives

The best alternative is probably the WP_CONTENT_DIR in my opinion. You can also use WP_CONTENT_URL, depending if you want a relative path or a full url.

Examples:
Here is an example of each followed by the output code:
<?php
echo WP_CONTENT_DIR;
echo “<br />“;
echo WP_CONTENT_URL;
echo “<br />“;
?>

/var/www/html/jafty.com/public_html/wp-content
http://jafty.com/wp-content

So now you know!

Want more? Here are some other ways to get similar paths or directories  from within a plugin file:

<?php
echo “<br>”;
echo plugins_url( ‘myscript.js’, __FILE__ );
echo “<br>”;
echo plugins_url();
echo “<br>”;
echo plugin_dir_url(__FILE__) ;
echo “<br>”;
echo plugin_dir_path(__FILE__) ;
echo “<br>”;
echo plugin_basename(__FILE__) ;
?>

The above would output the following lines if it were ran from a plugin on jafty.com:

http://jafty.com/wp-content/plugins/jafty_plugin_tester/test_code/myscript.js

http://jafty.com/wp-content/plugins

http://jafty.com/wp-content/plugins/jafty_plugin_tester/test_code

//var/www/html/jafty.com/public_html/wp-content/plugins/jafty_plugin_tester/test_code/

jafty_plugin_tester/test_code/wp_content_url.php

EDD Instant Updater WordPress Plugin

The EDD Instant Updater WordPress plugin is a plugin I created while working with a custom WordPress plugin that needed to have instant update notifications while using Easy Digital Downloads(EDD). EDD comes with it’s own updater class, but it uses the default WP standards which means you have to wait up to 12 hours after you push an update to get the notice in the WordPress dashboard! With the EDD Instant Updater plugin, you no longer have to wait, the plugin update notices come to you instantly! No more delays!

Interested? Contact Ian L of Jafty.com by email at linian11@yahoo.com for more information.

WordPress Plugin Admin Page Unwanted Scroll

I was working on a custom plugin for an important client today and one of the plugin’s admin pages would scroll half way down the page every time I landed on it and I couldn’t figure out why at first!

Long story short, I found out what was causing it was an inline JavaScript block of code, so If anyone has this issue in a WordPress admin page while making a plugin, try getting rid of the JavaScript and it should stop the page from scrolling as it did in my case.

If you experience something similar, please mention how you solved it in the comments.

Learning WooCommerce API Manger

What is WooCommerce API Manger?

WooCommerce API Manger is used to secure your software with API License Key activation, deactivation and automatic updates of WordPress plugins and/or themes. However it can also be used for some applications outside of WordPress as well, but we will be talking mostly about how to use it with a custom WordPress plugin.

Prerequisites

You need to at least make sure you have at least PHP Version 7.00. Here’s how you can check from the linux command line:

php -v

Type the above command and press enter and you should get results that look similar to this:

php-v

 

Alternative Solution to WooCommerce API Manager

You may have noticed this article isn’t complete. That is because I decided to go with a different system for selling WordPress plugins on my site with API keys, WooCommerce didn’t provide the level of support I needed and their documentation was poor. I discovered Easy Digital Downloads which was much simpler to deploy. Easy Digital Downloads(EDD) in combination with the EDD Software Licensing add-on and the EDD Instant Updater for plugins that I developed myself, became the ultimate solution for selling WordPress plugins outside of WordPress.org. If anyone is interested in how I did it, email me at linian11@yahoo.com and I can assist you.

 

 

Is Payoneer Better Than PayPal?

PayPal has worked for me for several years and, while they have been mostly good to me, when you do need help, their customer service is practically non-existent. I had a horrible experience with them recently that has made me decide not to use them any longer for a while. I’m almost exclusively a seller and almost never a buyer which makes PayPal a poor choice for me it seems now. I have never had a dispute in all the years I’ve used PayPal until recently and I can not forgive the way PayPal handled that dispute. If you want to hear my story, read on, if you want to get right to using Payoneer as I suggest if you are a seller of goods or services like me, use this link to sign up for Payoneer now:

https://share.payoneer.com/nav/Z0p1ilVwR6cXc5rK-hfGzOqAEhykGqdX9Q20h_PXFPXbJvtO-8cjY1wD_4Db8uwuUY0QGJmc9EVKLQ-V_ld1OA2

My Experience with PayPal

My bad experience that makes me want to completely stop using PayPal has to do with a former client of mine that filed a dispute after I had to inform them that I had to quit working for them because another client needed me(the other client that needed me has been a client for many years and the client I quit working for was new). When I quit working for the new client, he still owed me roughly $200 in my opinion. He had paid me a deposit of $200 when I started working with him because I always get a deposit to protect me from newer clients. I had completed a total of $400 worth of work before I quit working for him however, so really he still owed me $200. I was going to forgive the money he owed me however, since I had quit because I figured he wouldn’t pay it anyway. So, for being a nice guy, the new client rewards me by filing a dispute on PayPal asking me to return $95 to him! I was shocked, but had confidence that PayPal would see it for what it was, an attempt by a client to get his money back even though I had completd the work, Fraud. So I refused to return the money and he escalated his false claim. To my surprise, without doing any investigation what-so-ever, PayPal made a decision in his favor. Okay, so I lost, I could have handled that without closing my account, but the kicker is that they didn’t just reward the client the $95 he was asking for, they reversed the entire $200 payment he ad sent me! After losing the dispute, I first tried to call PayPal’s “customer support” and was told I would have to wait on hold for over an hour! I waited on hold regardless of the ridiculous amount of hold time, but the call was never answered so I gave up after over an hour of waiting for a human to speak with about my issue. Then I sent them sent an email asking them why and got a computer reply that had absolutely nothing to do with the questions I asked in the email. So obviously, I was getting nowhere and it is clear now that I just got ripped off for $200 by PayPal and my former client. So, hello Payoneer! I’ll let you all know how this new payment method works for me. Hopefully better than my experience with PayPal! Again, here’s the link for Payoneer if anyone else wants to check them out:

payoneer.com

My experience with Payoneer

So, while I am new to Payoneer, I will post my experiences here so others can benefit from them. First off, if you want or need to get your money immediately(Like you could with a PayPal Credit card if you were lucky enough to be approved), then Payoneer might not be the best service for you. I sent out my first invoice several days ago, on a Thursday to a client I completely trust and that client informed me that he paid the invoice immediately that same day, so the invoice was paid on Thursday. It is now the following Saturday and the invoice is yet to be even marked as paid in my Payoneer account. That kind of worries me. I read in their F.A.Q. that it can take from 3-5 business days, so luck me, it’s the weekend! Right? Oh well, so that means it has only been one business day so far and the fifth business day would be next Thursday. I have to say that it it in fact takes that long, I won’t be happy with the services at all. On the other hand, it the payment is in my account by Monday or Tuesday, I will be satisfied, not perfectly happy, but barely satisfied. I currently hate PayPal so much that I don’t mind waiting a few days to get paid another way. However, a week is too long, so I’ll let you all know asap when I can actually get the funds that were sent to me last Thursday. FYI, here’s an image from Payoneer’s website regarding information about the billing service I used to send my first invoice to my long-time trusted client:

payoneertable

How to Use jQuery UI Elements In a WordPress Plugin or Theme

Today I found myself once again needing to use jQuery in a new WordPress plugin I am developing for a client. I won’t lie, I often dread having to use jQuery within WordPress. It has been getting easier however, especially since WordPress version 3.3.x when they made many of the jQuery UI libraries part of the WordPress core. The trick is knowing that and knowing how to use them! For example I didn’t know about the jQuery UI libraries being part of the WP core until recently, so was just hacking my own jQuery into WordPress. The problem with hacking in a jQuery UI or any other jQuery code, is that it will usually break some other jQuery code in WordPress. Therefore I am putting together a quick reference guide on how to include jQuery and jQuery UI scripts in WordPress plugins and themes for my own reference and for other developers who can profit from this information.

First, here is a list of 35 jQueryUI elements already available within WordPress as of version 3.3.x:

Name: Enqueue Value: Dependency:
jQuery UI Core jquery-ui-core jquery
jQuery UI Widget jquery-ui-widget jquery
jQuery UI Accordion jquery-ui-accordion jquery
jQuery UI Autocomplete jquery-ui-autocomplete jquery
jQuery UI Button jquery-ui-button jquery
jQuery UI Datepicker jquery-ui-datepicker jquery
jQuery UI Dialog jquery-ui-dialog jquery
jQuery UI Draggable jquery-ui-draggable jquery
jQuery UI Droppable jquery-ui-droppable jquery
jQuery UI Menu jquery-ui-menu jquery
jQuery UI Mouse jquery-ui-mouse jquery
jQuery UI Position jquery-ui-position jquery
jQuery UI Progressbar jquery-ui-progressbar jquery
jQuery UI Selectable jquery-ui-selectable jquery
jQuery UI Resizable jquery-ui-resizable jquery
jQuery UI Selectmenu jquery-ui-selectmenu jquery
jQuery UI Sortable jquery-ui-sortable jquery
jQuery UI Slider jquery-ui-slider jquery
jQuery UI Spinner jquery-ui-spinner jquery
jQuery UI Tooltips jquery-ui-tooltip jquery
jQuery UI Tabs jquery-ui-tabs jquery
jQuery UI Effects jquery-effects-core jquery
jQuery UI Effects – Blind jquery-effects-blind jquery-effects-core
jQuery UI Effects – Bounce jquery-effects-bounce jquery-effects-core
jQuery UI Effects – Clip jquery-effects-clip jquery-effects-core
jQuery UI Effects – Drop jquery-effects-drop jquery-effects-core
jQuery UI Effects – Explode jquery-effects-explode jquery-effects-core
jQuery UI Effects – Fade jquery-effects-fade jquery-effects-core
jQuery UI Effects – Fold jquery-effects-fold jquery-effects-core
jQuery UI Effects – Highlight jquery-effects-highlight jquery-effects-core
jQuery UI Effects – Pulsate jquery-effects-pulsate jquery-effects-core
jQuery UI Effects – Scale jquery-effects-scale jquery-effects-core
jQuery UI Effects – Shake jquery-effects-shake jquery-effects-core
jQuery UI Effects – Slide jquery-effects-slide jquery-effects-core
jQuery UI Effects – Transfer jquery-effects-transfer jquery-effects-core

As you can see in the above table, the first 22 items in the list only require jQuery as a dependency. For those, you probably will only need to enqueue the value from the “Enqueue Value” column to make use of the library in your plugin or theme. You often will need to enqueue style for the jQuery library separately as well because as far as I know, WordPress doesn’t include many of the styles yet. the last dozen or so in the above table all require jquery-effects-core, so to use those, I believe you’ll need to enqueue that as well for them to work. For a complete list of other jQuery scripts that are already within the WordPress core, please visit the following codex page:

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

That page also explains usage of the wp-enqueue-script function to  a degree, but not as detailed as my special-use case described here.

How to Enqueue jQuery UI Elements in WordPress Plugin or Theme

Next I’m explaining how to include a jQuery UI library into your own WordPress plugin or theme. If you’re making a plugin, the code below will go into your plugin’s main file and if you’re working on a theme, then place the code below in the theme’s functions.php file. In the following code examples, I’ll demonstrate how to include both the jQuery UI element and the corresponding CSS file for using a datepicker in both the front-end and admin areas of WordPress. The code would be the same for any of the UI elements in the above table except that you would of course change the valuse to be enqueued for both the core jQuery file and the CSS file from googleapis.com.

PHP Code to use jQuery UI on the WordPress Front-End

function my_datepicker_function(){
//Enqueue date picker UI from WP core:
wp_enqueue_script(‘jquery-ui-datepicker’);
//Enqueue the jQuery UI theme css file from google:
wp_enqueue_style(‘e2b-admin-ui-css’,’http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css’,false,”1.9.0″,false);
}
add_action(‘wp_enqueue_scripts’, ‘my_datepicker_function’);

How to add PHP Code to Use jQuery UI on the WordPress Admin or Back-End

The PHP code to include the same datepicker UI in a WordPress back-end, admin page is nearly the same. The only difference is the hook we use in the add_action line at the end of the code is different. For front-end use, we used the wp_enqueue_scripts hook, but for admin use, we will use the admin_enqueue_scripts hook instead. That’s all folks!

Then simply include your HTML and  script tag wherever you want to use your datepicker in this case like so:

<div class=”wrap”>
<input type=”text” class=”datepicker” name=”datepicker” value=””/>
</div>

<script>
jQuery(function() {
    jQuery( “.datepicker” ).datepicker({
        dateFormat : “dd-mm-yy”
    });
});
</script>

Summary

the above example code is just for datepicker UI, but can easily be manipulated for any of the jQuery UI elements in the above table, so experiment and find the one that works for you. You will often need to google the jQuery UI element’s name and view an online demo of how it is used without WordPress to get exact code and then simply incorporate the above technique into what you learn. I did this with the sortable UI and it worked great. Good luck!

 

How to add Custom Admin Meta Boxes to a WordPress Custom Post Type

I decided to write this detailed tutorial on how to add custom field meta boxes to the WordPress admin mostly because I couldn’t find a decent description of how to do it anywhere online. Hopefully this will help others having trouble trying to learn how to add admin meta boxes with custom fields for a custom post type in WordPress. It is an essential step to learning WordPress plugin development.

Let’s dive in and learn some code because I believe that is the quickest and easiest way to learn this advanced WordPress method. I say it is an advanced subject because it is a little complex for beginners. If you are not sure how to start your own plugin yet in WordPress, then this topic may be too advanced for you. You should at least learn how to make a very basic WordPress plugin first, so feel free to read one of my more basic WordPress plugin tutorials first.

First of all, I’ll show you how to add a single meta box with a single field in it. It is also important to know that you can have more than one field inside a single meta box. It is equally important to know that you can have more than one meta box. Each meta box can have one or more fields in them. It just depends on your individual needs. Below is the basic code for how to add a custom post type with a custom field inside of an admin meta box. I’ll also include a basic plugin heading so you may follow along and create a working example to work from:

Adding a Custom Post Type to WordPress Plugin

<?php
/**
 * Plugin Name: Jafty Metabox Example Plugin
 * Plugin URI: http://jafty.com/blog/crash-course-on-wordpress-plugin-development/
 * Description: A Plugin that adds metaboxes to your WordPress blog or site.
 * Version: 1.0
 * Author: Ian L. of Jafty.com
 * Author URI: http://jafty.com
 * License: GPL2
 */
 

 //Add new Custom Post Type named videos:
add_action(‘init’, ‘create_video_posttype’);
function create_video_posttype(){
    register_post_type(‘videos’,
        array(
            ‘labels’ => array(
            ‘name’ => __(‘Videos’),
            ‘singular_name’ => __(‘Video’)
            ),
        ‘public’ => true,
        ‘has_archive’ => true,
        ‘rewrite’ => array(‘slug’ => ‘video’),
        )
    );
}//end create_video_posttype function

?>

Okay, now start a .php file and add the above code in green to the start of it. Name the file “jafty-metabox-example-plugin.php” and save it. Please NOTE: it is important to go into wp-admin/settings/permalinks and re-save those settings after activating a plugin with a custom post type or after adding a custom post type to a plugin. If you do not do this, the custom post type posts will not show up on the front end of your blog.

At this point, you should be able to upload the jafty-metabox-example-plugin.php file to your WordPress site’s plugins folder and activate it. If it works, you’ll see a new “Video” option in the left navigation menu of wp-admin as in the following photo:

videoCPT

Add a Metabox with a Custom Field to your CPT

Now here is the code to add to the end of the file you started above(just before the closing PHP tag) that will add a meta-box with a custom field inside of it to your plugin. It adds a field to the wp-admin edit screen for the videos CPT(custom post type):

//Add custom admin Meta Boxes:
add_action(‘add_meta_boxes’, ‘add_ians_metaboxes’);
function add_ians_metaboxes(){
//add meta box for Video type and description:
add_meta_box(‘meta_box_html_id’, ‘Video Details’, ‘video_details_function’, ‘videos’, ‘normal’, ‘high’);
}

//##################### Video Details Metabox: ################
function video_details_function() {
global $post;  
//Noncename needed to verify where the data originated
echo ‘<input type=”hidden” name=”eventmeta_noncename” id=”eventmeta_noncename” value=”‘ .
wp_create_nonce(plugin_basename(__FILE__)) . ‘” />’;

//Get video description data if its already been entered
$video_desc = get_post_meta($post->ID, ‘_video_desc’, true);
    
//Start video Description text field HTML:
?>
Video Description:
<input type=”text” name=”video_desc” value=”<?php echo $video_desc; ?>” class=”widefat” />
<?php
}//end video_details_function

Save the “jafty-metabox-example-plugin.php” file and update it on your site and click on the “Video” link in wp-admin and then click on “Add New” to see the add/edit screen for your new CPT. You will notice your  custom meta-box with the heading of “Video Details”. You will also notice the meta-box contains a custom field named “Video Description”. You can see both near the bottom of the photo below:

customField

Saving Custom Field Data

Your not quite done however. While the code above will display the metaboxes, it does not save the data as I soon discovered. To save the data, you’ll need to add this code directly after your video_details callback function:

//hook into save_post to save the meta box data:
add_action (‘save_post’, ‘save_video_desc’);

function save_video_desc($post_id) {
//verify the metadata is set
     if (isset( $_POST[‘video_desc’])) {
     //save the metadata
     update_post_meta ($post_id, ‘_video_desc’, strip_tags($_POST[‘video_desc’]));
     }
}

 

 Adding Multiple Meta-Boxes and Custom Fields

Next I’ll show you what our final plugin file would look like if we were to add another custom field to our meta-box and then another meta-box with yet another custom field inside of it. This way you can see how more than one meta-box is added and also how to add more than one field inside of a single meta-box. Here is the complete plugin code containing a total of two meta-boxes and three total custom fields:

<?php
/**
* Plugin Name: Jafty Metabox Example Plugin
* Plugin URI: http://jafty.com/blog/crash-course-on-wordpress-plugin-development/
* Description: A Plugin that adds metaboxes to your WordPress blog or site.
* Version: 1.0
* Author: Ian L. of Jafty.com
* Author URI: http://jafty.com
* License: GPL2
*/

//Add new Custom Post Type named videos:
add_action(‘init’, ‘create_video_posttype’);
function create_video_posttype(){
register_post_type(‘videos’,
array(
‘labels’ => array(
‘name’ => __(‘Videos’),
‘singular_name’ => __(‘Video’)
),
‘public’ => true,
‘has_archive’ => true,
‘rewrite’ => array(‘slug’ => ‘video’),
)
);
}//end create_video_posttype function

//Add custom admin Meta Boxes:
add_action(‘add_meta_boxes’, ‘add_ians_metaboxes’);
function add_ians_metaboxes(){
//add the first meta box for Video type and description:
add_meta_box(‘meta_box_html_id’, ‘Video Details’, ‘video_details_function’, ‘videos’, ‘normal’, ‘high’);
//add a second meta box for Video Rating
add_meta_box(‘meta_box_html_id2’, ‘Video Rating’, ‘video_rating_function’, ‘videos’, ‘normal’, ‘high’);
}
//################## Video Details Metabox: ####################
function video_details_function() {
global $post;

//Noncename needed to verify where the data originated
echo ‘<input type=”hidden” name=”eventmeta_noncename” id=”eventmeta_noncename” value=”‘ .
wp_create_nonce(plugin_basename(__FILE__)) . ‘” />’;

//Get the video type  if its already been entered
$video_type = get_post_meta($post->ID, ‘_video_type’, true);
// Get the video description if its already been entered
$video_desc = get_post_meta($post->ID, ‘_video_desc’, true);

//Start type select field HTML:
?>
Video Type: <select name=”video_type”>
<option value=”DVD”<?php if($video_type==”DVD”)echo ” selected”;?>>DVD<option>
<option value=”Blueray”<?php if($video_type==”Blueray”)echo ” selected”;?>>Blueray<option>
</select><br />
<?php
// Start video description field HTML:
?>
Video Description:
<input type=”text” name=”_location” value=”<?php echo $video_desc; ?>” class=”widefat” />
<?php
}//end video_details_function
//##################### Video Rating Metabox: ###################
function video_rating_function() {
global $post;

//Noncename needed to verify where the data originated
echo ‘<input type=”hidden” name=”eventmeta_noncename” id=”eventmeta_noncename” value=”‘ .
wp_create_nonce(plugin_basename(__FILE__)) . ‘” />’;

//Get the start_month data if its already been entered
$video_rating = get_post_meta($post->ID, ‘_video_rating’, true);

//Start type select field HTML:
?>
Video Type: <select name=”_video_rating”>
<option value=”R”<?php if($video_rating==”R”)echo ” selected”;?>>R<option>
<option value=”PG”<?php if($video_rating==”PG”)echo ” selected”;?>>PG<option>
</select><br />
<?php
}//end video_rating_function
?>

//add your save data hook and function to save all fields here:

//hook into save_post to save the meta box data:
add_action (‘save_post’, ‘save_video_data’);

function save_video_data($post_id) {
//verify the metadata is set
     if (isset( $_POST[‘video_desc’])) {
     //save the metadata
     update_post_meta ($post_id, ‘_video_type’, strip_tags($_POST[‘video_type’]));

    update_post_meta ($post_id, ‘_video_desc’, strip_tags($_POST[‘video_desc’]));

    update_post_meta ($post_id, ‘_video_rating, strip_tags($_POST[‘video_rating’]));
     }
}

That’s it! Save the above code in a PHP file and name it the same name as before and allow it to overwrite the original plugin file if you were following along and it will add another meta-box and a couple more custom fields to your custom post type. Now you should have enough information to be able to make your own custom admin meta-boxes and fields for your next WordPress plugin or theme. Here is an image of the two meta-boxes from when I tested the above code myself:

metaboxes

Summary

Now you should know more than enough to make your own plugin or custom theme with its own admin meta-boxes and custom fields for any custom post types you may have. It is important to know that you can also use any other type of form element in the above examples. Feel free to experiment and use textareas, radio buttons, checkboxes etc in your own code.

 

How to Stop Admin Emails Upon New User Registration in WordPress

It took me quite a bit of messing around to stop admin emails on new user registration to my WordPress site today, so I’m documenting the final solution here. The key is the pluggable function named wp_new_user_notification, but simply replacing the function in your theme’s functions.php file does not always(or maybe ever) work, so the final solution I found to work was to replace the pluggable wp_new_user_notification function inside a very simply light-weight plugin. Simply copy and paste the code below into a file and name it Disable_User_Notifications_To_Admin.php. Then upload it to your site’s plugins directory and go to wp-admin and activate it. Simple, easy, quick and DONE!

 

<?php
/**
 * @package Disable_User_Notifications_To_Admin
 * @version 1.0
 */
/*
Plugin Name: Disable User Notifications To Admin
Plugin URI: http://jafty.com/blog
Description: This is just a simple plugin to stop those annoying admin emails each time a new user registers to your site. simply change the value of linian11@yahoo.com in the main plugin file with the email you do not want to recieve notifications at and it will block them.
Version: 1.0
Author URI: http://jafty.com
*/
/*
change the value of linian11@yahoo.com below with the email you do not want to recieve notifications at and it will block them.
*/
if(!function_exists(‘wp_new_user_notification’)) :

function wp_new_user_notification($user_id, $plaintext_pass = ”) {
    $user = get_userdata($user_id);
    $blogname = wp_specialchars_decode(get_option(‘blogname’), ENT_QUOTES);

    if ( empty($plaintext_pass) )
        return;

    $message  = sprintf(__(‘Username: %s’), $user->user_login) . “\r\n”;
    $message .= sprintf(__(‘Password: %s’), $plaintext_pass) . “\r\n”;
    $message .= wp_login_url() . “\r\n”;
if($user->user_email != “linian11@yahoo.com”)
    wp_mail($user->user_email, sprintf(__(‘[%s] Your username and password’), $blogname), $message);

}
endif;

?>

Summary

That’s pretty much guaranteed to work if nothing else has.

 

Sell PHP, JavaScript, C++, C# and Other Scripts and Tools on Jafty.com

Yes, we have started a store on Jafty.com which can be found at Jafty.com/shop. Currently shoppers can find a limited collection of my own scripts and tools for sale. I would like to give my readers a chance to sell their own script and tools here as well, so I am opening it to the public upon approval by me of course. As long as I can see that your scripts are useful and have a potential that someone visiting my site will purchase them, I will publish them. To submit your script for review, simply send me an email at linian11@yahoo.com with a link to your script or attach it to the email and include the amount you expect to receive for each sale made and I will promptly give you a decision on whether or not we will sell your items on Jafty.com.

Email Ian at linian11@yahoo.com to sell your scripts today! Visit our script and tool shop at Jafty.com/shop

Creating a Web Development Environment

This week, I decided it was time to upgrade my web development tools so I contacted the professionals at SEO Root and got right into business. When you reach my age and have been coding for over 20 years, you have to upgrade every once in a while. I am doing this because I know there are faster and better ways to do what I do everyday. I also wanted to document the new system I create for myself as a seasoned web developer so that those of you just starting out can gain some insight.

Defining your Development Needs

First, I had to layout what my needs as a web developer were. I simply made a list of the technologies I use every day and some I use regularly but not every day necessarily and ordered the list in order of priority. The first items on my list are technologies I use the most:

  1. PHP
  2. HTML
  3. CSS
  4. JavaScript
  5. MySQL
  6. WordPress
  7. Woocommerce
  8.  jQuery
  9. Photoshop
  10. SEO
  11. Three.js 3D programming
  12. FTP
  13. Perl
  14. C++
  15. C#
  16. Ajax
  17. Blender
  18. Gimp
  19. Unity 3D Development
  20. XHTML
  21. XML

As you can see, I use over 20 web technologies in my day to day work and I didn’t even list them all, but those are the most significant ones off the top of my head that I use. My goal is to put together a work environment with the most important of those technologies in mind, and so have hired SEO consulting services to aid me with this. Ultimately I wish to create an environment that focuses on speed and the ability to make the top technologies I use to work together in a more organized fashion. For example an app that allows me to code in many languages and preview server-side code live in a local server would be one of the primary objectives of my new routine.

With that in mind, I am going to narrow down my above list to what I use in my day to day work from which I actually make money from and do the most. Those would be mostly the ones at the top of my list, but this gives me the opportunity to rethink what I need the most and come up with a work environment that best facilitates my needs as a web developer. Here’s what I came up with in the end:

  • PHP
  • HTML
  • CSS
  • JavaScript
  • MySQL
  • WordPress
  • Woocommerce
  • Graphic Design
  • SEO
  • FTP
  • Perl

Several of the items in my first list were related to JavaScript such as jQuery, Three.js and Ajax, so really, my main objective is to just have JavaScript available in my work environment and it will basically cover all the related technologies as well for the most part. There is no way we are going to make an efficient work environment with over 20 technologies, so it is important to narrow your list down as much as is practical. There were also a few different methods of creating graphics on my first list and instead of naming Photoshop, Gimp, Blender, etc, I just put “Graphic Design” on my short-list because that enables me to think in more broad terms about what applications I can use that might be able to accomplish the same tasks as those tools all rolled up in a more advanced tool(if that is possible). I will need to consult the specialists from superior web design in Ottawa to make sure I am doing it the right way.  If you  look to design and build your new website, or redesign and upgrade your existing site, visit https://www.akeaweb.com/accessibility-consulting/ .

Searching for Applications

My next task was to find programs and applications that will help speed up the web development process. First, I will list the programs and applications I use currently and from there figure out where I can make improvements. So I copy and paste my short-list from above and add after each technology what tool or program I use to accomplish tasks related to each technology:

  • PHP ——————- Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • HTML —————– Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • CSS ——————– Notepad++, Filezilla, Firefox, IE, Safari, Chrome
  • JavaScript ———– Notepad++ , Filezilla, Firefox, IE, Safari, Chrome
  • MySQL —————- Notepad++, PHPMyAdmin, Firefox, Putty
  • WordPress ———– Notepad++, wp-admin, Filezilla, PHPMyAdmin, Firefox, IE, Safari, Chrome, Putty,
  • Woocommerce —– Notepad++, wp-admin, Filezilla, PHPMyAdmin, Firefox, IE, Safari, Chrome
  • Graphic Design – Photoshop, Gimp, Blender, Unity, MakeHuman, FileZilla, Firefox, Notepad++
  • SEO ——————– Notepad++, Firefox, Various Service Providers
  • FTP ——————– Filezilla, Notepad++
  • Perl ——————– Notepad++, Putty, Filezilla

So from the above exercise, I was able to make a comprehensive list of the programs and applications I use when doing my web development work:

  1. Notepad++
  2. wp-admin
  3. Filezilla
  4. PHPMyAdmin
  5. Firefox
  6. Internet Explorer(IE)
  7. Safari
  8. Chrome
  9. Putty
  10. Photoshop
  11. Gimp
  12. Blender
  13. Unity
  14. MakeHuman

So out of those 14 programs, I don’t actually use them all everyday and I use some more than others. For example, I am more of a programmer than a graphic designer. That’s why I call myself a “Web Developer” and not a “Web Designer”. So numbers 10 – 14 on the list can go into my “Nice to Have” category and do not require crucial changes since I only use them every once in a while and it’s not a huge deal to keep using what I use now for those. If you are primarily a web designer however, these applications would be higher up on your list of tools you use and you WOULD want to give more thought to whether you can find better tools and tools that can combine the abilities of several of those. For example, Photoshop can do everything Gimp can do for the most part, so you might want to drop Gimp as a regular tool and use Photoshop more often. Then Unity, Blender and MakeHuman are all 3D modeling tools used more for video game development than web development, but if you use these regularly, you can probably search and find a tool that does most of what you need to do using those tools all rolled up in one good tool. Actually Unity is close. I try to learn to do what models and textures I can right in Unity instead of going to Blender to create them and then import them into Unity which takes more time, but sometimes it is still necessary to do.

Anyway, being first and foremost a web developer and not a designer, the tools most important to me right now are the first ones on my list and can be narrowed down to these:

  1. Notepad++ is what I currently use for most of my coding needs.
  2. PHPMyAdmin is a must have for all of my MySQL database manipulation needs currently.
  3. Filezilla is what I always use to download files from client’s web servers. Then I edit them and upload them back to the server using Filezilla once again.
  4. Firefox is my web browser of choice since it is by far the most standards compliant of all the available popular web browsers. The others listed above are only used at the end of a project to check for cross-browser compatibility and there is no real way to get around having to use them all to properly debug your web applications.
  5. Putty is a great tool I also use often to access client’s web servers for just about anything that I cannot do through the Filezilla FTP program. Tasks I use Putty for include tweaking PHP settings, changing ownership of files and editing server configuration files.

The next thing I have to ask myself is where can I make improvements in my development process and what tools are involved. After that I can search for better tools to accomplish those goals. From what I gather after examining my own habits and tools that I use, I figure the most improvement can be made in the areas of FTP, Code editing and Previewing the results of the code I write.

I came up with the above conclusion by thinking about where it seems like I waste the most time. Also I kept in mind what is possible to change and I figured that recent developments in developer tools probably will allow me to be able to improve the way I edit code, the way I update files and the way I view server-side scripts while in the process of coding them. Here’s my current most common process in my day to day work routine:

  1. I go to Firefox and locate the problem on a client’s website or the area of the website that they may want something added to.
  2. Then, I open Filezilla and locate the files involved that need editing on the server and download them to my desktop for editing.
  3. Next, I will normally open Notepad++ and work on the PHP, HTML, CSS and/or JavaScript code until a portion of the solution is accomplished.
  4.  Then I have to use Filezilla again to upload that file back to the web server for testing.
  5. After that, I open the webpage in Firefox to see if it works and to plan what I have to do next.
  6. I go back to Notepad++ and make more changes.
  7. I upload with Filezilla again and again view the progress in Firefox and keep repeating steps 4,5 and 6 until the changes appear correct.
  8. Then finally, I check the progress in all other popular browsers such as IE, Chrome and Safari to make sure it all works. Again here I have to repeat steps four through six some more until all problems are resolved with cross-browser compatibility.

As you can see, there are some seriously repeated functions that can take up a lot of precious development time in my current process. The best way to speed the process up would be to eliminate the process of having to upload the files to he server every time I make a round of changes and view it in a browser then go back to notepad++. With this acknowledgement in mind, I need to find a tool that allows me to do the following important steps in my web development process:

  1. edit several types of code in one place.
  2. get the code to the server seamlessly for testing.
  3. and view the output in a browser.

So the best place for improvement in my process is within those three steps. If I could find the perfect tool to accomplish all three, that would be perfect.

Finding Tools to Improve your Workflow

So, while looking for tools to accomplish these feats, Here is what I found.

CyberDuck

The first one I tried after reading reviews and program descriptions all across the web, was a not-so-well-known application called CyberDuck. After testing CyberDuck for about a week or so, I found that it met most of these needs, but had it’s pros and cons like any other application. Let’s examine those pros and cons:

CyberDuck Pros:

  • allows for the importing of FTP connection information from Filezille to CyberDuck. This is great because if you have a lot of clients like I do, you have a lot of FTP connections and it would take a lot of time to copy them all manually. In CyberDuck, they call FTP connections “bookmarks” this was strange to me and I didn’t know what they were for the first day or so, but once I figured out what they were, I was able to use the application much more efficiently.
  • CyberDuck has an FTP application built in.
  • It allows you to link your favorite text editor or code editor to the FTP function so all you do is click on a file in the server’s document tree and it opens in an editor on your local machine! So, it downloads a copy of the file and opens it in your editor in other words. So in my case, I click on a file in the document tree and it opens up in Notepad++ for editing.
  • When I save the file after making changes in Notepad++, it automatically uploads the changes to the remote server without me having to do anything but click on “Save” in Notepad++. This saves a lot of time. Even though I am actually using two programs, CyberDuck and Notepad++, it seems like I’m only using one because there is a nice seamless integration of the two performed within CyberDuck.

Cons of Using CyberDuck

There are not a lot of cons, but the ones that bothered me were:

  1. It drops the connection to the server more often than Filezilla did it seems like.
  2. While it combined two of my three main functnionalities I was seeking, it did not allow for viewing of the code changes live on the server. I still would have to go to Firefox to do that.

All in all, CyberDuck is a great tool. It is still new and has some bugs to work out, but I will definitely follow it and use it while looking for a better solution. Perhaps it will evolve into that perfect solution in a future version. Who knows.

CodeLobster PHP Edition

Next I got an email to let me know of a new program called CodeLobster that was supposed to be the perfect PHP code editor and much more. I am giving it a try right now, so I’ll have to come back with most of my review of CodeLobster, but right out of the box I notice that it has a wide range of code editing abilities and features, is expandable and very well made. The only drawbacks I’ve noticed so far are minor such as the word wrap feature breaks up words in bad places and there is no spell check that I can find for editing plain .txt files. It seems great for editing PHP code so far though.

To get expert help regarding SEO and web designing, go to TheDigitalSwarm.com and opt for their services.

Want to learn more about SEO? Check out these relative books from Amazon:

How to Edit Woocommerce Shop Pages

In order to edit your Woocommerce shop pages such as the main shop link and other pages within Woocommerce , the best way to get started is to go to the woocommerce directory at plugins/oocommerce and copy the woocommerce/templates folder into your current theme directory. Then rename the templates directory you copied into your themes main directory to woocommerce. Now you have all the templates for Woocommerce pages being overridden by the templates in the woocommerce folder inside your current theme! Now you can edit the pages without having to worry about messing up the original Woocommerce files.

Create a Dropdown of Product Categories in Woocommerce

A recent project demanded that I create a drop-down list of Woocommerce product categories for an admin page in a plugin I was creating. Here is the PHP and HTML code that accomplished the task:

<form method=”post” action=””>
<?php $args1 = array(‘taxonomy’  => ‘product_cat’); ?>
  <?php wp_dropdown_categories( $args1 ); ?>
<input type=”submit” name=”cat_sel” value=”SELECT PRODUCT CATEGORY” />
</form><hr />

Retrieve Selected Category in Form Processing Script

Now to retrieve the value, you will use the post variable named cat like so:

$chosen_cat = $_POST[‘cat’];

…and that will return a product ID. If you need a product name, here is cool PHP function I found that returns the post name/slug when feeding the function the ID we just stored in $chosen_cat above:

function get_product_category_by_id( $category_id ) {
    $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
    return $term['name'];
}
$product_category = get_product_category_by_id( $your_category_id );

 

How to Remove Fields from Woocommerce Edit Address Form

To remove the country field from the checkout and “edit my address” pages, you have to remember to remove it not only from the billing address but the shipping address as well. Here is the example code to accomplish this. Paste the below code into functions.php of your current theme and it should work perfect.

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
add_filter( 'woocommerce_billing_fields' , 'custom_override_billing_fields' );
add_filter( 'woocommerce_shipping_fields' , 'custom_override_shipping_fields' );

function custom_override_checkout_fields( $fields ) {
  unset($fields['billing']['billing_country']);
  unset($fields['shipping']['shipping_country']);
  return $fields;
}

function custom_override_billing_fields( $fields ) {
  unset($fields['billing_country']);
  return $fields;
}

function custom_override_shipping_fields( $fields ) {
  unset($fields['shipping_country']);
  return $fields;
}

Now you can alter the above code to fit your needs. Some of the field names you may want to remove include:
billing_first_name
billing_last_name
billing_email
billing_phone