How to disable specific wordpress plugins from automatic upgrade

Sometime there is need to use some plugins in an application and you have the need to customize it UI or functionality to meet your business requirements.

You install the plugins and make the necessary changes to meet the configuration.

Few week later, you discover that your plugins has lost it custom formatting and the custom workflow due to recent upgrade of the plugins version.
Huhh, now what to do.

Option 1: You may look into your past backupfile to restore the plugins from your back up folder to restore the customized codes. This could be risky or not feasible. For example you may not be having the backup of the plugin , secondly you might get it but may be confused on which version you have to restore, because you had made many backup folder.

Option 2: The recommended way is to disable you customized plugins to get auto upgrade. What you need to do is put this below code in your theme functions.php file.

function disableSpecificPlugins( $value ) {
if( isset( $value->response[‘plugin-folder-name/plugin-name.php’] ) ) {
unset( $value->response[‘plugin-folder-name/plugin-name.php’] );
}
return $value;
}
add_filter( ‘site_transient_update_plugins’, ‘disableSpecificPlugins’ );

Here:

“plugin-folder-name” => plugin folder name

“plugin-name.php” => plugin main file. In most cases , the file name is same as plugin folder name. But it can also be index.hp

Drupal 8 how to get value of the webform submission in webform confirmation twig file

Put the below code in youractivetheme.theme file

/**
* Implements hook_preprocess_HOOK().
*/

function [theme]_preprocess_webform_confirmation(&$vars) {
if ($vars['webform']->id() == 'put your webform id') {
// Set your custom message here
$markup = t('Thank you for your feedback.');
$vars['message']['#markup'] = $markup;
}
}

/// How to customise the message based on the submitted value

/**
* Implements hook_preprocess_HOOK().
*/

function [theme]_preprocess_webform_confirmation(&$vars)
{
if ($vars['webform']->id() == 'put your webform id')
{
// Get the submitted form value using the below command
$submittedFormValues = $vars['webform_submission']->getRawData();
if($submittedFormValues['field_name'] == 'some condition or value'){
$markup = t('display message 1');
}
else
{
$markup = t('display message 2');
}
// Set your custom message here
$vars['message']['#markup'] = $markup;
}
}

How to search string in all files in a folder and sub folder recursivelly

How to use “grep” command in linux or macos to find text inside all files in a folder and including subdirectories

Command for the same is
grep -rl "string to search" /absolute-path/to/folder/

-r (or –recursive) option is used to traverse also all sub-directories of /path
-l (or –files-with-matches) option is used to only print filenames of matching files
-i ( for ignore case sensitive)

If you’re looking for lines matching in files, then use the below command

grep -Hrn "string to search" /absolute-path/to/folder/

-H causes the filename to be printed (implied when multiple files are searched)
-r does a recursive search
-n causes the line number to be printed
/absolute-path/to/folder/ can be . (dot) to search in the current directory

php session handler using mysql on multiple server setup or load balancer setup

Many a time you have to host your website on multiple server such as load balancer to server high traffic website. It is obvious that if i have a load balancer or multiple servers in use, the user’s session is coming from 1 server so if the user is pushed to say server 2 or server 3 then does that mean the user’s session will expire or how to make it work as normal?

I have multi-session checks, so if a user logs-in from a different location it will auto sign them out like we see on bank websites. And this will affect the user journey and create issue to the users? Is there anything I need to do at the database level?

Yes you can do it by using custom session management using MySql or any other database.

Option 1: You can use the common recommended approach suggested by many tech gigs as here https://www.php.net/manual/en/function.session-set-save-handler.php

But sometime, the server configuration doesn’t allow to overwrite the server default session handler, Hence you need to go with some different approach.

Option 2: The way i found the solution.

I created a session handler class using mysql database, create method to start, write, read, unset and destroy the session variable.

Below is the example usage of the same.

Usage Example Just include this file at the top, where you want to manage the session using session data

require_once ‘handleSession.php’; // Make sure to set the Mysql Database credential appropiately

To set session data in DB

Case 1: Set a single session data, pass the key and value in array $cstmSessionHandler->cstm_sess_write(array(‘developer1’=>’1vinod’));

Case 2: To set two dimensional session data, pass the key and value in array as below $newData[‘aaa’][‘ffff’] = ‘1111’; $newData[‘aaa’][‘bbb’] = ‘222’; $cstmSessionHandler->cstm_sess_write($newData);

To read session data

Case 1: To read only a single session variable Pass the session key. $sessionValuesArr = $cstmSessionHandler->cstm_sess_read(‘aaa’);

Case 2: To read all the session which are active. Dont pass any argument $sessionValuesArr = $cstmSessionHandler->cstm_sess_read();

To unset specific session variable $cstmSessionHandler->cstm_sess_unset(‘aaa’);

To destroy all the session variable $cstmSessionHandler->cstm_sess_destroy();

You can download the source code and example from gitlab

https://gitlab.com/vinodkram/php-session-handler-using-mysql-on-load-balancer-setup

WordPress permalink pagination not working

Say for example i have created a custom post type. I have implemented pagination for the same.

When i call this url

http://localhost.dm/news/multi-media-gallery/page/2/, it show page not found.

But if i try with

http://localhost.dm/news/multi-media-gallery?page=2,  it work.

Now to make the pagination work with permalink you need to add the following rewrite rule in your theme functions.php

add_action(‘init’, function ()
{
add_rewrite_rule(‘(.?.+?)/page/?([0-9]{1,})/?$’, ‘index.php?pagename=$matches[1]&paged=$matches[2]’, ‘top’); flush_rewrite_rules();
}, 1000);

Jquery set input value and trigger on blur event

I want to trigger an event every time i click on select on any element by id

First i will try to set the input value by the following code

pickedvalue = jQuery(‘#someElementId’).val();

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)); // use parseInt if the input type is “number” else not required.

After setting the new value to the other element i wanted to fire “on blur” event so to achieve the same use the below code.

jQuery(‘#anotherInputElement’).val(parseInt(pickedvalue)).trigger(“change”).blur();

 

–Happy Coding

Add default blank value for select option in contact form 7 wordpress

Normally when you use contact form 7 plugin , for dropdown select option, there is no option to set blank value for the first option to validate the select field.

For example, what we have in wordpress contact form 7

<select name=”your_field_name”>
<option value=””>—</option>
<option value=”yes”>Yes</option>
<option value=”no”>No</option>
</select>

But in actual scenario, i want to display the label for the first option as “–Select Value–” with empty value.
To make the same change, you can use the dropdown code as below
[select* your_field_name_ class:form-select class:required first_as_label “–Select Value–” “Yes” “No”]

In the above code “first_as_label” is important parameter. It instruct the plugin to use the first option as label with default empty value. So the generated output look as below

<select name=”your_field_name”>
<option value=””>–Select Value–</option>
<option value=”yes”>Yes</option>
<option value=”no”>No</option>
</select>

If you have any queries, you can write back to us or comment in the comment section.

How to show or hide yii2 gridview action button conditionally

In Yii2 Gridview normally to display the action button we have the following chunk of code

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
]
];

The output you see as below:

Now you have a scenario, to show the edit button only when the “Zone status” is active. So you have to add the additional line

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => [],
'header'=>'Actions',
'template' => '{view} {update} {delete}',
'visibleButtons'=>[
'delete'=> function($model){
return $model->zone_status!='deleted';
},
'view'=> function($model){
return $model->zone_status!='active';
},
]
],
];

Now let me explain what changes were done to display the view button , when zone_status is active.

So the “visibleButtons” control the display of the action button based on the value returned by

function($model){
return $model->zone_status!='active';
}

If the condition hold true, view button will be displayed else not.

Next Level:

You can take this to next level. i.e. if you want to control the button style and the default url for each action, you can do it as below:

$columns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'description:ntext',
'status',
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => [],
'header'=>'Actions',
'buttons' => [
'view' => function ($url,$model,$key) {
return Html::a('<button>Details</button>', Url::home()."zone/view?id=".$model->id);
},
'delete' => function ($url,$model,$key) {
if($model->zone_status != 'deleted') {
return Html::a('<button class="bk-custom-btn">Delete</button>', Url::home()."delete?id=".$model->id);
}
},
'update' => function ($url,$model,$key) {
$url = ['zone/update?id='.$model->id];
return Html::a('<button class="bk-edit-btn">Edit</button>',$url);
},
],
'template' => '{view} {update} {delete}',
'visibleButtons'=>[
'delete'=> function($model){
return $model->zone_status!='deleted';
},
'view'=> function($model){
return $model->zone_status=='active';
},
]
],
];

The final output as below:

How to create date wise apache error log and access log

By default apache write the access log and error log in the single file. Later it grow in sizes over days and then when you have to debug you find the issue from the apache log, it become difficult to open and read the file. And over a time, the log size bigger so big that, many of the file editor fail to load the file.

Default Logformat
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

So apache come with a inbuilt program called rotatelogs.
First you need to check if rotatelogs is present on your server or not.

To check if rotatelogs is present type the below command
> whereis rotatelogs

The output of the command will be as below
rotatelogs: /usr/bin/rotatelogs /usr/share/man/man8/rotatelogs.8.gz

This “/usr/bin/rotatelogs” indicate that rotatelogs program is present

Now to split your errorlog and accesslog by date, you need to comment the default log format
#ErrorLog ${APACHE_LOG_DIR}/error.log
#CustomLog ${APACHE_LOG_DIR}/access.log combined

and write down the below format.

CustomLog “| /usr/bin/rotatelogs -l /var/log/apache2/access.%Y.%m.%d.log 86400” common
ErrorLog “| /usr/bin/rotatelogs -l /var/log/apache2/error.%Y.%m.%d.log 86400”

What this does is…everyday a new error log and access log file will be created like error.2020.04.03.log and access.2020.04.03.log respectively.

To explore more option for the custom logging you can refer the apache project page http://httpd.apache.org/docs/current/programs/rotatelogs.html

export mysql database – mysql dump

When you have access to the command line and you have the export large database, you will not be able to export from phpmyadmin.

Hence mysql provide you handy method to export the database from the command line. Below are various options, you can use while exporting the database.

——databases – This allows you to specify the databases that you want to backup. You can also specify certain tables that you want to backup. If you want to do a full backup of all of the databases, then leave out this option
——add-drop-database – This will insert a DROP DATABASE statement before each CREATE DATABASE statement. This is useful if you need to import the data to an existing MySQL instance where you want to overwrite the existing data. You can also use this to import your backup onto a new MySQL instance, and it will create the databases and tables for you.
——triggers – this will include the triggers for each dumped table
——routines – this will include the stored routines (procedures and functions) from the dumped databases
——events – this will include any events from the dumped databases
——set-gtid-purged=OFF – since I am using replication on this database (it is the master), I like to include this in case I want to create a new slave using the data that I have dumped. This option enables control over global transaction identifiers (GTID) information written to the dump file, by indicating whether to add a SET @@global.gtid_purged statement to the output.
——user – The MySQL user name you want to use
——password – Again, you can add the actual value of the password (ex. ——password=mypassword), but it is less secure than typing in the password manually. This is useful for when you want to put the backup in a script, in cron or in Windows Task Scheduler.
——single-transaction – Since I am using InnoDB tables, I will want to use this option.
——no-create-db – don’t create database
——no-create-info – don’t create table structure
——extended-insert=FALSE => Each row as seperate insert querry

Syntax : mysqldump ——triggers ——routines ——databases databasename ——user=root ——password > database_export_file_name.sql
Example : mysqldump ——no-create-db ——triggers ——extended-insert=FALSE ——routines ——databases mydatabase ——user=root ——password  > mydatabase.sql

Sometime you have to type the absolute path for mysqldump executable path to execute the above command for example.

Example : /var/mysqlFolder/bin/mysqldump ——no-create-db ——triggers ——extended-insert=FALSE ——routines ——databases mydatabase ——user=root ——password  > mydatabase.sql

More option you can explore on Maria DB website