show a message when updating a custom widget in wordpress backend - wordpress

I'm developing a custom wordpress widget. The widget needs some data from the user and needs to check this data server-side.
I wrote the code that checks the data inside the function 'update' of the widget. When I press the button save of the widget the function update got called correctly and my validation is executed.
public function update( $new_instance, $old_instance ) {
$instance = array();
foreach ($this->fields as $field) {
$fieldName = $field['name'];
$instance[$fieldName] =
(!empty($new_instance[$fieldName]) strip_tags($new_instance[$fieldName]) : '' );
}
$check = validate($new_instance);
return $instance;
}
What I need is to display a message to the user based on the result of the validation. How can I do this? For what I've seen the function update is called through ajax so I can't use an admin notice.
Is it possible?How can I do that?

Try below code
add_action('admin_notices', 'misha_custom_order_status_notices');
function misha_custom_order_status_notices() {
global $pagenow, $typenow;
if( get_transient( 'fx-admin-notice-panel' )){
echo "<div class=\"updated\"><p>Custom notification comes here</p></div>";
}
}
public function update( $new_instance, $old_instance ) {
$instance = array();
foreach ($this->fields as $field) {
$fieldName = $field['name'];
$instance[$fieldName] =
(!empty($new_instance[$fieldName])?
strip_tags($new_instance[$fieldName]) :
''
);
}
$check = validate($new_instance);
set_transient( 'fx-admin-notice-panel', true, 5 );
return $instance;
}

Related

Can't Change property value through a method in a WordPress plugin

I'm trying to check if WooCommerce is active or not, I created a property with with a default value of false, then I created a method to check if WooCommerce is active using is_plugin_active() and admin_init hook, if active the value of the property must be updated to true: here is the code:
class MyClass{
public $woo_active = false;
public function __construct(){
add_action( 'admin_init', array( $this, 'check_if_woo_active' ) );
}
// check if WooCommerce is active
public function check_if_woo_active(){
if( is_plugin_active( 'woocommerce/woocommerce.php' ) ){
$this->woo_active = true;
}
}
// is_woo_active()
public function is_woo_active(){
return $this->woo_active;
}
}
$var = new MyClass();
var_dump( $var->is_woo_active() );
the issue is that var_dump returns false even if WooCommerce is active, BUT, if I use var_dump inside the function check_if_woo_active(), it returns true.
Why the property value is not updated? thanks
Updated:
The Second Solution as #helgatheviking sugested works fine, also this works very well and short
class MyClass{
// check if WooCommerce is active
public function is_woo_active(){
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if( is_plugin_active( 'woocommerce/woocommerce.php' ) ){
return true;
}else{
return false;
}
}
}
$var = new MyClass();
var_dump( $var->is_woo_active() );
If I had to guess, then $var = new MyClass(); is run before admin_init so the check_if_woo_active() isn't run.
Couple things you could do. First, I will usually launch my plugin on the woocommerce_loaded hook. That way I am 100% sure WooCommerce is running.
class MyClass{
protected static $instance = null;
/**
* Main MyClass Instance
*
* Ensures only one instance of MyClass is loaded or can be loaded.
*
* #static
* #see MyClass()
* #return MyClass - Main instance
* #since 0.1.0
*/
public static function instance() {
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof MyClass ) ) {
self::$instance = new MyClass();
}
return self::$instance;
}
public function __construct(){
// Do what you want, WC is definitely active
}
}
/**
* Returns the main instance of class.
*
* #return MyClass
*/
function MyClass() {
return MyClass::instance();
}
// Launch the class if WooCommerce is loaded:
add_action( 'woocommerce_loaded', 'MyClass' );
You could also mimic what WooCommerce does with their premium plugins and check the option that stores the active plugins:
class MyClass{
private static $active_plugins;
public static function get_active_plugins() {
self::$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() ){
self::$active_plugins = array_merge( self::$active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
}
}
// check if WooCommerce is active
public static function check_if_woo_active() {
if ( ! self::$active_plugins ) self::get_active_plugins();
return in_array( 'woocommerce/woocommerce.php', self::$active_plugins ) || array_key_exists( 'woocommerce/woocommerce.php', self::$active_plugins );
}
}
var_dump( MyClass::check_if_woo_active() );

Submit form within controller extension - SilverStripe 3.4.0

I'm trying to submit a form created within an controller extension. After Submitting, it throws me an error
Sadly I don't know why or how to solve this, without losing the build in validation and so.
I could manually change the form action to "doSectionForm", than I'll receive the forms data but have lost all the validation.
Here's an excerpt of my code.
<?php
class SectionsPageControllerExtension extends DataExtension {
private static $allowed_actions = [
'SectionForm'
];
public function SectionForm($id = null) {
$fields = FieldList::create(
HiddenField::create('SectionFormID')
->setValue($id)
);
$required = RequiredFields::create();
$actions = FieldList::create(
FormAction::create('doSectionForm', 'Absenden')
);
$form = Form::create($this->owner, 'SectionForm', $fields, $actions, $required);
// $form->setFormAction($this->owner->Link() . 'doSectionForm');
return $form;
}
}
public function doSectionForm($data) {
echo '<pre>';
print_r($data);
}
}
Actions on controllers usually receive an instance of the SS_HTTPRequest as parameter. This is in conflict with your $id = null parameter. Thus the error-message.
You shouldn't use parameters for your form methods, or if you absolutely need it for the templates, make sure to check if the $id parameter is of type SS_HTTPRequest first (this will be the case when the form is being submitted).
A simple workaround would be to rewrite your code as follows:
$fields = FieldList::create(
HiddenField::create('SectionFormID')->setValue(
($id instanceof SS_HTTPRequest) ? $id->postVar('SectionFormID') : $id
)
);

wordpress - how can I block email sending by role?

I have an educational Wordpress site where students have the role 'child' and adults have the role 'subscriber'. I need to prevent emails being sent to the 'child' users (by Woocommerce - but I think they are sent via the mail function in Wordpress).
Is there a line I can add in functions.php to stop mail being sent to specific roles?
Thanks in advance
Maria
I think it might be possible to adjust the email recipients via a filter in the get_recipient() method.
/**
* get_recipient function.
*
* #return string
*/
public function get_recipient() {
return apply_filters( 'woocommerce_email_recipient_' . $this->id, $this->recipient, $this->object );
}
Let's take for example the new order email. Here's it's trigger() method:
/**
* trigger function.
*
* #access public
* #return void
*/
function trigger( $order_id ) {
if ( $order_id ) {
$this->object = wc_get_order( $order_id );
$this->find['order-date'] = '{order_date}';
$this->find['order-number'] = '{order_number}';
$this->replace['order-date'] = date_i18n( wc_date_format(), strtotime( $this->object->order_date ) );
$this->replace['order-number'] = $this->object->get_order_number();
}
if ( ! $this->is_enabled() || ! $this->get_recipient() ) {
return;
}
$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
}
Specifically
if ( ! $this->is_enabled() || ! $this->get_recipient() ) {
which says if there is no recipient then the email won't send. Also $this->object = wc_get_order( $order_id ); tells us that the $order object is passed to the get_recipient_$id filter.
The id of the new order email is "customer_completed_order" as shown in the class constructor for the email.
SO, putting that all together we can filter the recipient for new order emails:
add_filter( 'so_29896856_block_emails', 'woocommerce_email_recipient_customer_completed_order', 10, 2 );
function so_29896856_block_emails( $recipient, $order ) {
if( isset( $order->customer_user ) ){
$user = new WP_User( $customer_user );
if ( in_array( 'child', (array) $user->roles ) ) {
$recipient = false;
}
}
return $recipient;
}
However, this assumes that the recipient is a single string (if an array it would kill all the recipients and not just the child... though by the default the new order email is sent to the billing email address.
Also, note that I didn't test this at all, so your mileage may vary.

How do I show an error on a WP_Widget

How do I display an error in the form, a flash message or someway, indicating what he did wrong?
The code is something like this:
class My_Widget extends WP_Widget {
public function update( $new_instance, $old_instance ) {
if (!valid($new_instance))
// How do I notify the user with a custom message
return false;
else
return $new_instance
}
}
I know that returning false prevents the options from being saved, but the user won't know why.
Try this one,
public function update( $new_instance, $old_instance ) {
$old_instance['errors'] = array();
if (!valid($new_instance)) {
$$old_instance['errors']['myfield'] = 'Custom error mesasage goes here';
// How do I notify the user with a custom message
return false;
//return $old_instance;
}
else
return $new_instance
}
public function form($instance) {
$myfieldMsg = (isset($instance['errors']) && isset($instance['errors']['myfield'])) ? $instance['errors']['myfield']) : null;
echo $myfieldMsg;
....

wordpress plugin shortcodes buffer

My developed wordpress plugin which is activated with a shortcode is breaking my admin area saying that header cannot be modified. Digging a bit deeper I got to know that if the function is getting echoed than I have this problem if I use return than is ok. But the problem with return is: that I use ajax to retrieve html and in this case no output is generated.
message Cannot modify header information - headers already sent by (output started at /var/www.... web/wordpress/wp-admin/admin-header.php
MyClass{
public function __construct()
public $data;
{
require_once(dirname(__FILE__) . '/class/class.another.php');
$this->data = new Another();
add_action( 'init', array( &$this, 'init' ) );
}
public function init()
{
add_shortcode( 'my_shortcode', array ($this, 'shortcode') );
if(isset($_POST['id'])){
$param = $this->data->output_ajax_html($_POST['id']);
echo $this->shortcode_html_extended($param);
//this part breaks the buffer without echo is working but the contertn won't show up
}
}
public function shortcode()
{
add_shortcode( 'my_shortcode', array ($this, 'shortcode_html') );
}
public function shortcode_html()
{
$html = "";
$html .="";
return $html;
}
public function shortcode_html_extended($param)
{
$html = "";
//mixed with php
$html .="";
return $html;
}
}
$test = new MyClass();

Resources