Using Woocommerce Hooks in a Wordpress Plugin - wordpress

I created a sample plugin for using woocommerce hooks. Basically my requirement was to add some javascript to the footer of the wordpress page based on some woocommerce hooks. However, those hooks don't seem to get fired at all. I have woocommerce installed. If I put the same code in theme's function file, the javsacript gets added, but not from the plugin.
In the plugin, there are three actions. The first action is a plain wp_footer action which works and js is added. the remaining two are woocommerce actions and are not getting fired. Can anyone please help? I am sure I am calling the hooks the wrong way but I can't figure out.
<?php
/*
* Plugin Name: Demo Woo Plugin
* Plugin URI:
* Description:
* Version: 1.0
* Author:
* Author URI:
* License: GPLv2
*/
/*
*/
if(!class_exists('Demowoo')) {
class Demowoo {
var $plugin_url;
var $plugin_dir;
public function __construct() {
global $woocommerce;
$this->plugin_url = trailingslashit( WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)) );
$this->plugin_dir = trailingslashit( plugin_dir_path(__FILE__) );
add_action( 'wp_footer', array($this, 'demowoo_content') );
// initiate woocommerce hooks and activities
add_action('woocommerce_init', array($this, 'on_woocommerce_init'));
add_action('woocommerce_after_cart_contents', 'cart_page_visited');
}
public function install() {
}
public function deactivate() {
}
/**
* Append the required javascript.
*/
public function demowoo_content() {
echo '<script type="text/javascript">console.log("Demo Plugin Content");</script>';
}
public function on_woocommerce_init() {
add_action('wp_footer', 'woocommerce_initialized');
}
public function woocommerce_initialized() {
echo '<script type="text/javascript">console.log("JS through woo commerce init.");</script>';
}
public function cart_page_visited() {
add_action('wp_footer', 'demo_woo_add_to_cart');
}
public function demo_woo_add_to_cart() {
echo '<script type="text/javascript">console.log("JS for added_to_cart on the cart page");</script>';
}
} // End class
$Demowoo = new Demowoo();
if($Demowoo) {
register_activation_hook( __FILE__, array(&$Demowoo, 'install'));
}
}

All your calls of add_action should use the form array($this, 'method_name') in their second parameter, like the first hook on wp_footer. This is because you are hooking methods of an object, not functions.
If you just write the name of the method WP will look for a global function with that name, not a class method. Since there are no global functions with those names, nothing happens.
The array syntax allows WP to know not only the method name but which object it should be invoked from. PHP cannot just invoke an object method without having an instance of the object, so you need to provide one to the hooking system. With the style to define plugins that you're using here the object instance is usually always $this.

Related

How to use pluggables functions on plugins

I need to use functions such as wp_insert_user and wp_update_user in a plugin, but theses functions call others functions who are not yet loaded (such as get_user_by or get_userdata).
If I require the pluggable.php file where I use theses functions it works, but messing with WordPress load orders seems a pretty bad idea to me.
How would you use theses functions in a plugin ?
After looking at how ACF plugin do it, I've found a solution, instead of calling the function at the plugin load, I just add it to the action init.
require 'myClass.php';
$myClass = new myClass();
add_action('init', [$myClass, 'myFunction']);
I would even suggest to use a main class for your plugins and in the __construct hook your logic to init and/or plugins_loaded.
class MyPlugin {
public function __construct() {
add_action( 'plugins_loaded', [$this, 'plugins_loaded'] );
add_action( 'init', [$this, 'init'] );
}
public function plugins_loaded() {
// pluggables functions are available here
}
public function init() {
// pluggables functions are available here
}
}
new MyPlugin();

Too may redirects when i use the wp_redirect() function

I'm developing a plugin using the OOP approach but I'm running into a many redirects issue.
I want my plugin to redirect to a page when some conditions are not met after plugin activation. I keep getting To many redirects... error message.
My code is as shown below:
if (! defined('WPINC')) die;
if (! class_exists('AwesomePlugin')) {
class AwesomePlugin {
public function __construct(){
//Register admin menus
add_action('admin_menu', [$this, add_menu]);
//Init plugin
add_action('admin_init', [$this, 'init_plugin']);
}
/**
*
* Init plugin
*/
public function init_plugin(){
if(!isset(get_option("some_option"))){
wp_redirect("admin.php?page=some-page"); exit; //This gives too many redirects
}
wp_redirect('admin.php?page=dashboard'); exit;
}
/**
* Add menu and submenu items
*/
public function add_menu(){
add_menu_page(
'Dashboard', 'Dashboard', 'manage_options', 'dashboard',
[__CLASS__, 'load_dashboard_view'],
plugins_url('logo.png', __FILE__)
);
add_submenu_page(
'', 'Signup page', 'Signup page', 'manage_options',
'sign-up', [__CLASS__, 'load_signup_view']
);
}
/**
* Dashboard page
*/
public function load_dashboard_view(){
include(plugin_dir_path(__FILE__) . 'dashboard.php');
}
/**
* Signup page
*/
public function load_signup_view(){
include(plugin_dir_path(__FILE__) . 'signup.php');
}
}
AwesomePlugin()
}
What am I missing?
EDIT: I understand that no matter the page I'm loading, the init_plugin function keeps firing. As a result, it keeps redirecting the user to the sign-up, thus the many redirect error message. How do I solve this?
I believe that the issue is caused when you initially call your file with the above code.
You should call the file that your code is in with the include_once('path-to-your-file/your-php-file.php')
It's pretty simple. You check happens every time admin is initiated, literally on every page of /wp-admin and (I think) every AJAX call.
If you need to check this only on a certain page of your plugin management menu, you could use $current_screen global or get_current_screen() and use ID property of the object to check if the current page is where you want to do your checks. You can use Query Monitor (under admin screen), to see what exactly ID you page gets as well as lots of other stuff you might find useful when debugging.

Gravity Forms gform_after_submission not working from a plugin?

I have a plugin that I've written that is trying to call the gforms_after_submission hook. For some reason it isn't calling the function. I see in Gravity Forms documentation that it says I have to call gform_after_submission from the functions file - is there any reason I can't call it from the plugin? I've tested with the mail function, and the function admin_init is triggering.
<?php
class Infusionsoft_GformsPDF {
public function __construct() {
add_action( 'admin_init', array( $this, 'admin_init' ) );
}
/**
* Should call my function, but doesn't
*/
public function admin_init() {
add_action('gform_after_submission', 'handle_file', 10, 2);
}
/**
* Get the file URL and post it to Infusionsoft
*/
public function handle_file($entry, $form){
mail('myemail#email.com', 'Handle File was triggered', 'yippee');
}
}
the problem here is that you've added the function call to the admin_init hook. The admin_init hook is only triggered when the user accesses the admin area, but you're submitting a form here, an action taking place on the front-end of your site outside of the admin area.
It's a simple fix :-) Just use the front-end initialization hook instead — init
Also check out this reference for the actions that are typically run when a page is loaded, on the front of your site and the admin area:
http://codex.wordpress.org/Plugin_API/Action_Reference

How to show text in a page on Wordpress whithin a plugin

I am developing a plugin for a website.(Which is my first plugin for Wordpress)
The basic functionality is querying the database and in specific pages show the data from the database with a specific style instead of the content from the pages.
So far I managed to show some text in every specific page.
This is my code after some basic configurations:
global $wpdb;
global $wp_query;
add_action( 'wp', 'check_which_page' );
function check_which_page()
{
$page_type=get_post_type();
$page_id=get_the_ID();
//echo $page_id;
switch($page_id)
{
case 50:technologyPage();break;
case 82:medicalPage();break;
}
}
function technologyPage()
{
return print "Technology";
}
function salesPage()
{
return print "Sales";
}
function medicalPage()
{
return print "Medical";
}
I've read this post, but I couldn't solve my problem.
WordPress replace content of a page (plugin)
I already read the Wordpress documentation but I havent find anything there.
I found myself a solution, using shortcodes.
global $wpdb;
global $wp_query;
add_shortcode( 'sector_page_display', 'check_which_page' );
function check_which_page()
{
$page_type=get_post_type();
$page_id=get_the_ID();
//echo $page_id;
switch($page_id)
{
case 50:technologyPage();break;
case 82:medicalPage();break;
}
}
function technologyPage()
{
return print "Technology";
}
function medicalPage()
{
return print "Medical";
}
See that instead of add_action I changed to add_shortcode
Then on everypage I will use to show info from the database I add
[sector_page_display]
in the page, so it call my method. You can add variables in there if you want.
You'll want to run that code before WordPress has fully loaded.
Try this
global $wpdb;
global $wp_query;
add_action( 'init', 'check_which_page' );
function check_which_page()
{
$page_type=get_post_type();
$page_id=get_the_ID();
//echo $page_id;
switch($page_id)
{
case 50:technologyPage();break;
case 82:medicalPage();break;
}
}
function technologyPage()
{
return print "Technology";
}
function salesPage()
{
return print "Sales";
}
function medicalPage()
{
return print "Medical";
}
I changed the add_action to now run the code when WordPress is being initialized.

Why won't WordPress load thickbox and media-upload scripts?

I'm working on a plugin that uses thickbox and media-upload to set some images. Neither will load using this code:
function add_my_files() {
echo 'happy happy happy';
wp_register_style( 'adminstyles', plugins_url('/css/slider.css', __FILE__));
wp_enqueue_style( 'adminstyles' );
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('hdjs',plugins_url('/js/slider.js', __FILE__),array('media-upload','thickbox'),'',true);
wp_enqueue_script('hdjs');
}
add_action( 'admin_init', 'add_my_files' );
my css and js files load but not thickbox and media-upload.
Thanks
The correct hook to include your asset files in WP is admin_enqueue_scripts:
NOTE: I recommend you too use get_current_screen (see is_my_admin_screen() definition below) to just include your js/css files when you actually needed.
add_action('admin_enqueue_scripts', 'add_my_files');
function add_my_files()
{
/*
* a good WP citizen only loads
* their javascript/css where it is needed
*/
if ( ! is_my_admin_screen()) // defined below
return;
wp_register_style('adminstyles', plugins_url('/css/slider.css', __FILE__));
wp_enqueue_style('adminstyles');
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('hdjs', plugins_url('/js/slider.js', __FILE__), array('media-upload', 'thickbox'), '', true);
wp_enqueue_script('hdjs');
}
function is_my_admin_screen()
{
$screen = get_current_screen();
if (is_object($screen) && $screen->id == 'my_plugin_page_id') // var_dump($screen->id); find your own id
return true;
else
return false;
}
ref: http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
ref: http://codex.wordpress.org/Function_Reference/get_current_screen
Besides hopefully you are using a class to wrap all your plugin or you will have worse problems than this.
Please feedback. I am very interested in this issue because WP plugins puts food and beers on my table.

Resources