I've re-edited this question: is possible to before to show the output in point 2 pass a variable to global color (point 3) like a global variable or something?
class myclass
{
public function init()
{
global $shortcode_tags;
add_shortcode( MYSHORTCODE, array( 'myclass', 'shortcode' ) );
// * point 1
return;
}
public function shortcode( )
{
// *point2
}
function globalcolor($color)
{
echo '<style>body{color:' .$color . '}</style>' . "\n";
// * point 3
}
}
add_action( 'wphead', array( 'myclass', 'globalcolor' ) );
add_action( 'init', array( 'myclass', 'init' ) );
PS. right now im reading about custom fields.enter code here
do_action() is called by WordPress, you want add_action().
The action init comes way too early. You call the class now even for the backend, for AJAX requests etc. Use the hook template_redirect which is called on the frontend only.
You cannot send the color value the way you tried. See the sample code for a working example.
Sample code:
class My_Plugin {
/**
* Container for your color value.
* #var string
*/
static $color;
public static function init()
{
// Set the color value as a class member.
self::$color = '#345';
// Class methods are addressed with an array of the object or the
// class name and the function name.
add_action( 'wp_head', array ( __CLASS__, 'print_color' ) );
}
public static function print_color()
{
// In action you have to print/echo to get an output.
print '<style>body{color:' . self::$color . '}</style>';
}
}
add_action( 'template_redirect', array ( 'My_Plugin', 'init' ) );
I strongly recommend https://wordpress.stackexchange.com/ to ask more questions on WordPress. :)
Related
In a plugin I'm working on, I'm trying to replace the OOTB customer-completed-order email with a template in the plugin
Constructor:
define( 'BKF_WC_EMAIL_PATH', plugin_dir_path( __FILE__ ) );
add_filter('wc_get_template', array($this, 'bkf_customer_completed_order_template'), PHP_INT_MAX, 5);
Function:
function bkf_customer_completed_order_template($template, $template_name, $args, $template_path, $default_path) {
if( $template_name == 'emails/customer-completed-order.php' ) {
$template = trailingslashit(BKF_WC_EMAIL_PATH) . 'templates/' . $template_name;
return $template;
}
}
note the template is still pulling the default woo one
Any thoughts/ideas are welcome!
Worked it out!
Instead of the method used in my original question, here's what worked for me:
I created a new class (similar to woocommerce/includes/emails/class-wc-email-customer-completed-order.php) - for demo purposes we'll call it My_Custom_Class
I then called like so in my constructor for the parent class I was working on:
add_action('woocommerce_email_classes', array( $this, 'bk_register_email' ), PHP_INT_MAX, 1 );
And added this function:
public function bk_register_email( $emails ) {
require_once 'emails/my-custom-class.php';
$emails['WC_Email_Customer_Completed_Order'] = new My_Custom_Class();
return $emails;
}
I'm trying to add a single class (my-class) to an element in a WordPress post (LearnDash Theme). I fount out that it can be done using a hook via add_filter, but no how I could figure it out.
The sample code that I found looks like this:
add_filter( 'body_class', 'custom_body_class' );
/**
* Add custom field body class(es) to the body classes.
*
* It accepts values from a per-page custom field, and only outputs when viewing a singular static Page.
*
* #param array $classes Existing body classes.
* #return array Amended body classes.
*/
function custom_body_class( array $classes ) {
$new_class = is_page() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
In this sample code the class is added to pages only but I need to add it to "posts". I tried is_post() but it didn't work out. I even tried it on a page, but didn't work also.
In my case I want to add a class to an element with ID learndash-page-content.
Existing code:
<div id="learndash-page-content">...</div>
What I'm struggling to do:
<div id="learndash-page-content" class="my-class">...</div>
What do I need to do to get it working?
If that is indeed the syntax of the element, you might want to try string manipulation on the output (which you will capture like this:)
function start_modify_html() {
ob_start();
}
function end_modify_html() {
$html = ob_get_clean();
$html = str_replace( '<div id="learndash-page-content">', '<div id="learndash-page-content" class="my-class">', $html );
echo $html;
}
add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );
I am trying to create a custom type plugin. And I am not really sure what is wrong with my code since there is no errors but the plugin is not working even tho I already activate it.
defined( 'ABSPATH' ) or die( 'No script kiddies please!' ); // copied in codex
class LouisPlugin
{
function __contruct() {
add_action ('init',array($this, 'custom_post_type'));
}
function activate(){
}
function deactivate(){
}
function unsintall(){
}
function custom_post_type(){
register_post_type('job_list',['public' => true, 'label'=>'job_list']);
}
}
if (class_exists('LouisPlugin')){
$louisPlugin = new LouisPlugin();
}
register_activation_hook( __FILE__, array($louisPlugin, 'activate' ) );
register_deactivation_hook(__FILE__, array($louisPlugin,'deactivate'));
please check your code
function __contruct() {
add_action ('init',array($this, 'custom_post_type'));
}
the __construct method name was incorrect I think this can be one reason
function __construct() {
add_action ('init',array($this, 'custom_post_type'));
}
I know how to create a single page and archive page but now I am trying to move everything into a custom plugin. So far I created my custom post type, 'location' and I created my files
/templates/archive-location.php
/templates/single-location.php
How can I get mysite.com/locations to read my archive-location.php all within my custom plugin.
***Update****
I was able to get my single page to work. Now how do I make it so this can be included in any site? For instance I don't know their layout, should I include header and footer?
I need it so if I remove my plugin, mysite.com/locations doesn't exist anymore.
Here is a code for dynamically create custom templates during custom plugin is activated.
suppose i want to create two page first and second and i would like to assign custom templates to it.
Put below the code in your custom plugin's main file like index file of your custom plugin.
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'news_plugin_install');
/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'news_plugin_remove' );
function news_plugin_install() {
$newsGagPages = array(
'First Page',
'Second Page'
);
foreach ($newsGagPages as $postTitle) {
$my_post = array(
'post_title' =>$postTitle,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
'post_status'=>'publish');
if(!get_page_by_title($postTitle))
{
$pageID = wp_insert_post($my_post,true);
}
if($postTitle =="First Page" ){
add_post_meta( $pageID, '_wp_page_template', 'template-first.php' );
}
if($postTitle =="Second Page" ){
add_post_meta( $pageID, '_wp_page_template', 'template-second.php' );
}
}
}
class PageTemplater {
/* A Unique Identifier */
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter('page_attributes_dropdown_pages_args',array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter('wp_insert_post_data',array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter('template_include',array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'template-first.php' => 'First',
'template-second'=>'Second ',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta($post->ID, '_wp_page_template', true)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta($post->ID, '_wp_page_template', true);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}else {
echo $file;
}
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
I am trying to add some site-specific functionality to the Wordpress plugin Appointments+. When a user is making an appointment, they select certain services and enter information into some fields for confirmation.
What I want to do is add some code so the extra information fields are related to which service they choose. For example, if they choose Service A, they have to fill in some information and those fields are validated. But if they choose Service B, hide the fields and skip the validation.
Here is an example of the original code:
function post_confirmation() {
...some extra stuff
$values = explode( ":", $_POST["value"] );
$location = $values[0];
$service = $values[1];
do_action('app-additional_fields-validate');
...more stuff
}
Here is the kind of thing I want to do, but not alter this original plugin file:
function post_confirmation() {
...some extra stuff
$values = explode( ":", $_POST["value"] );
$location = $values[0];
$service = $values[1];
if (($service == 1) || ($service == 3)) {
do_action('app-additional_fields-validate');
}
...more stuff
}
I admit that I am new to using hooks and filters. I want to disable/enable that action based on a variable in the function. How can I do that with another hook/filter?
Thank you.
Unhook the hook used for calling post_confirmation and override this function from your functions.php like
remove_action( 'current_action_hook', 'post_confirmation' );
add_action( 'current_Action_hook', 'post_custom_confirmation' );
function post_custom_confirmation(){
...some extra stuff
$values = explode( ":", $_POST["value"] );
$location = $values[0];
$service = $values[1];
if (($service == 1) || ($service == 3)) {
do_action('app-additional_fields-validate');
}
...more stuff
}
I think this should work, I have used this way during a woocommerce plugin development before nearly 2 months below is working code example , so that if you need any modification on code above, you can take reference .
remove_action( 'woocommerce_checkout_order_review', 'woocommerce_order_review', 10 );
add_action( 'woocommerce_checkout_order_review', 'pk_order_review', 10, 1 );
function pk_order_review($template) {
global $woocommerce;
$template = wc_get_template ( 'checkout/review-order.php', FALSE, FALSE, untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/templates/');
return $template;
exit;
}
Another way you can do it is
add_action( 'app-additional_fields-validate', 'foo' );
function foo(){
if (($service == 1) || ($service == 3)) {
/* Your stuffs */
}
}
This is actually part answer, part new question. If that is possible to do here.
So, I finally found a way to affect the desired function.
The function I was trying to modify is contained in a class so, I did something like this:
class my_Check extends Appointments {
function __construct() {
$this->unregister_parent_hook();
add_action( 'wp_ajax_post_confirmation', array( $this, 'post_confirmation' ) );
add_action( 'wp_ajax_nopriv_post_confirmation', array( $this, 'post_confirmation' ) );
}
function unregister_parent_hook() {
global $appointments; //this was the object created with the parent class
remove_action( 'wp_ajax_post_confirmation', array( $appointments, 'post_confirmation' ) );
remove_action( 'wp_ajax_nopriv_post_confirmation', array( $appointments, 'post_confirmation' ) );
}
function post_confirmation() {
...do the stuff with my mods...
}
}
$new_Check = new my_Check();
Only, I have a new problem now. The parent class does a lot more in the __construct() (many 'add_action()'s, etc.). And $this is populated with a lot more data. The problem is, these other things and data do not seem to be carrying over into the child class. I tried adding a parent::__construct() in the child's __construct() function, but that did not seem to work.
The code with my mods works except for things that need more data in the $this carried over from the parent class.
How can I maintain all the parent class's variable, functions, hooks & filters, etc. into the child class?