Wordpress Ninija form redirect - wordpress

I tried to redirect to another form/page by condition.
I used Ninja Forms (3.3.) at Wordpress 4.9..
I created webhook.
following is code
add_action( 'generate_token', 'generate_token_callback' );
/**
* #param $form_data array
* #return void
*/
function generate_token_callback( $form_data ){
global $ninja_forms_processing;
$form_id = $form_data[ 'form_id' ];
$form_fields = $form_data[ 'fields' ];
foreach( $form_fields as $field ){
$field_id = $field[ 'id' ];
$field_key = $field[ 'key' ];
$field_value = $field[ 'value' ];
// Example Field Key comparison
if( 'my_field' == $field[ 'key' ] ){
// This is the field that you are looking for.
}
}
error_log( "get token - " . $form_id, 0 );
$form_settings = $form_data[ 'settings' ];
$form_title = $form_data[ 'settings' ][ 'title' ];
error_log( "get token 2 - " . $form_id, 0 );
if($form_id == 2) {
$url = get_home_url() . "/thankyou" ;
wp_redirect( $url );
}else{
$url = get_home_url() . "/error" ;
wp_redirect( $url );
}
}
The wp_redirect is not working. How can I?
Updated ---
after adding the "exit();"
but not redirect to thankyou page.
Updated ---
done by
https://www.inkthemes.com/how-you-can-easily-create-customized-form-in-wordpress/

You only miss the exit(). So just add it after wp_redirect. whenever use wp_redirect use exit() method.
if($form_id == 2) {
$url = get_home_url() . "/thankyou" ;
wp_redirect( $url );
exit(); // always exit
}else{
$url = get_home_url() . "/error" ;
wp_redirect( $url );
exit(); // always exit
}

Related

How to do email validation by blocking some email domain names in wordpress?

I need to validate an email field in gravity form. We have some known list of email domains and need to validate whether that domains present or not and If that domains present means we need to show the error message.
What is the best way to implement that? Any plugin suggestions?
This is possible with the GW_Email_Domain_Validator snippet here:
https://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
Full snippet as of July 18, 2020 included here. Use the link above to get the latest version.
<?php
/**
* Gravity Wiz // Gravity Forms // Email Domain Validator
*
* This snippets allows you to exclude a list of invalid domains or include a list of valid domains for your Gravity Form Email fields.
*
* #version 1.4
* #author David Smith <david#gravitywiz.com>
* #license GPL-2.0+
* #link http://gravitywiz.com/banlimit-email-domains-for-gravity-form-email-fields/
*/
class GW_Email_Domain_Validator {
private $_args;
function __construct($args) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false,
'domains' => false,
'validation_message' => __( 'Sorry, <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'ban' // also accepts "limit"
) );
// convert field ID to an array for consistency, it can be passed as an array or a single ID
if($this->_args['field_id'] && !is_array($this->_args['field_id']))
$this->_args['field_id'] = array($this->_args['field_id']);
$form_filter = $this->_args['form_id'] ? "_{$this->_args['form_id']}" : '';
add_filter("gform_validation{$form_filter}", array($this, 'validate'));
}
function validate($validation_result) {
$form = $validation_result['form'];
foreach($form['fields'] as &$field) {
// if this is not an email field, skip
if(RGFormsModel::get_input_type($field) != 'email')
continue;
// if field ID was passed and current field is not in that array, skip
if($this->_args['field_id'] && !in_array($field['id'], $this->_args['field_id']))
continue;
$page_number = GFFormDisplay::get_source_page( $form['id'] );
if( $page_number > 0 && $field->pageNumber != $page_number ) {
continue;
}
if( GFFormsModel::is_field_hidden( $form, $field, array() ) ) {
continue;
}
$domain = $this->get_email_domain($field);
// if domain is valid OR if the email field is empty, skip
if($this->is_domain_valid($domain) || empty($domain))
continue;
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = sprintf($this->_args['validation_message'], $domain);
}
$validation_result['form'] = $form;
return $validation_result;
}
function get_email_domain( $field ) {
$email = explode( '#', rgpost( "input_{$field['id']}" ) );
return trim( rgar( $email, 1 ) );
}
function is_domain_valid( $domain ) {
$mode = $this->_args['mode'];
$domain = strtolower( $domain );
foreach( $this->_args['domains'] as $_domain ) {
$_domain = strtolower( $_domain );
$full_match = $domain == $_domain;
$suffix_match = strpos( $_domain, '.' ) === 0 && $this->str_ends_with( $domain, $_domain );
$has_match = $full_match || $suffix_match;
if( $mode == 'ban' && $has_match ) {
return false;
} else if( $mode == 'limit' && $has_match ) {
return true;
}
}
return $mode == 'limit' ? false : true;
}
function str_ends_with( $string, $text ) {
$length = strlen( $string );
$text_length = strlen( $text );
if( $text_length > $length ) {
return false;
}
return substr_compare( $string, $text, $length - $text_length, $text_length ) === 0;
}
}
To only accept submissions from a given email domain you can do something like this:
new GW_Email_Domain_Validator( array(
'form_id' => 326,
'field_id' => 1,
'domains' => array( 'gmail.com', 'hotmail.com', '.co.uk' ),
'validation_message' => __( 'Oh no! <strong>%s</strong> email accounts are not eligible for this form.' ),
'mode' => 'limit'
) );

Get product ID inside a custom WooCommerce/Plugin filter

I am trying to change the product edit url which is created from this plugins function:
function dokan_edit_product_url( $product ) {
if ( ! $product instanceof WC_Product ) {
$product = wc_get_product( $product );
}
if ( ! $product ) {
return false;
}
if ( 'publish' === $product->get_status() ) {
$url = trailingslashit( get_permalink( $product->get_id() ) ) . 'edit/';
} else {
$url = add_query_arg(
[
'product_id' => $product->get_id(),
'action' => 'edit',
],
dokan_get_navigation_url( 'products' )
);
}
return apply_filters( 'dokan_get_edit_product_url', $url, $product );
}
You can see it has a apply_filters available. So I am trying to create a filter to modify the URL to be: example.com/edit-product/product-id
add_filter( 'dokan_get_edit_product_url', function() {
// I need to get the PRODUCT ID here somehow.
$url = 'example.com/dashboard/edit-product' . $product_id;
return $url;
} );
How can I get the product ID in my filter? I need to grab the product ID and attach it to: example.com/dashboard/edit-product/ + product_id
Here is one attempt:
add_filter( 'dokan_get_edit_product_url', function( $product ) {
$product = wc_get_product( $product );
var_dump($product);
return $url;
} );
Result:
/app/filters.php:175:boolean false
Following a suggestion in the comments from #howard-e, I was simply missing global $product;
Here is my full filter:
add_filter( 'dokan_get_edit_product_url', function( $product ) {
global $product;
$url = dokan_get_navigation_url() . 'edit-product?product_id=' . $product->get_id();
return $url;
} );
Obviously the format of the $url is unique to my set up, but worth posting the full code anyway.

wordpress I have class file which use for paypal express checkout Instead of express checkout i want to it replace to adaptive payment

/**
* Class PayPal
* #package Bookly\Lib\Payment
*/
class PayPal
{
// Array for cleaning PayPal request
static public $remove_parameters = array( 'action', 'token', 'PayerID', 'ab_fid', 'error_msg', 'type' );
/**
* The array of products for checkout
*
* #var array
*/
protected $products = array();
/**
* Send the Express Checkout NVP request
*
* #param $form_id
* #throws \Exception
*/
public function send_EC_Request( $form_id )
{
if ( !session_id() ) {
#session_start();
}
if ( ! count( $this->products ) ) {
throw new \Exception( 'Products not found!' );
}
$total = 0;
// create the data to send on PayPal
$data = array(
'SOLUTIONTYPE' => 'Sole',
'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
'PAYMENTREQUEST_0_CURRENCYCODE' => get_option( 'ab_currency' ),
'NOSHIPPING' => 1,
'RETURNURL' => add_query_arg( array( 'action' => 'ab-paypal-return', 'ab_fid' => $form_id ), Lib\Utils\Common::getCurrentPageURL() ),
'CANCELURL' => add_query_arg( array( 'action' => 'ab-paypal-cancel', 'ab_fid' => $form_id ), Lib\Utils\Common::getCurrentPageURL() )
);
foreach ( $this->products as $index => $product ) {
$data[ 'L_PAYMENTREQUEST_0_NAME' . $index ] = $product->name;
$data[ 'L_PAYMENTREQUEST_0_AMT' . $index ] = $product->price;
$data[ 'L_PAYMENTREQUEST_0_QTY' . $index ] = $product->qty;
$total += ( $product->qty * $product->price );
}
$data['PAYMENTREQUEST_0_AMT'] = $total;
$data['PAYMENTREQUEST_0_ITEMAMT'] = $total;
echo "<pre>";
print_r($data);
exit;
// send the request to PayPal
$response = self::sendNvpRequest( 'SetExpressCheckout', $data );
// Respond according to message we receive from PayPal
if ( 'SUCCESS' == strtoupper( $response['ACK'] ) || 'SUCCESSWITHWARNING' == strtoupper( $response['ACK'] ) ) {
//$paypalurl = 'https://www' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&useraction=commit&token=' . urldecode( $response['TOKEN'] );
$paypalurl = 'https://www' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/cgi-bin/webscr?cmd=_ap-payment&useraction=commit&token=' . urldecode( $response['TOKEN'] );
header( 'Location: ' . $paypalurl );
exit;
} else {
header( 'Location: ' . wp_sanitize_redirect( add_query_arg( array( 'action' => 'ab-paypal-error', 'ab_fid' => $form_id, 'error_msg' => str_replace( ' ', '%20', $response['L_LONGMESSAGE0'] ) ), Lib\Utils\Common::getCurrentPageURL() ) ) );
exit;
}
}
/**
* Send the NVP Request to the PayPal
*
* #param $method
* #param array $data
* #return array
*/
public function sendNvpRequest( $method, array $data )
{
$url = 'https://api-3t' . get_option( 'ab_paypal_ec_mode' ) . '.paypal.com/nvp';
$curl = new Lib\Curl\Curl();
$curl->options['CURLOPT_SSL_VERIFYPEER'] = false;
$curl->options['CURLOPT_SSL_VERIFYHOST'] = false;
$data['METHOD'] = $method;
$data['VERSION'] = '76.0';
$data['USER'] = get_option( 'ab_paypal_api_username' );
$data['PWD'] = get_option( 'ab_paypal_api_password' );
$data['SIGNATURE'] = get_option( 'ab_paypal_api_signature' );
$httpResponse = $curl->post( $url, $data );
if ( ! $httpResponse ) {
exit( $curl->error() );
}
// Extract the response details.
parse_str( $httpResponse, $PayPalResponse );
if ( ! array_key_exists( 'ACK', $PayPalResponse ) ) {
exit( 'Invalid HTTP Response for POST request to ' . $url );
}
return $PayPalResponse;
}
public static function renderForm( $form_id )
{
$html = '<form method="post" class="ab-paypal-form">';
$html .= '<input type="hidden" name="action" value="ab-paypal-checkout"/>';
$html .= '<input type="hidden" name="ab_fid" value="' . $form_id . '"/>';
$html .= '<button class="ab-left ab-back-step ab-btn ladda-button" data-style="zoom-in" data-spinner-size="40"><span class="ladda-label">' . Lib\Utils\Common::getTranslatedOption( 'ab_appearance_text_button_back' ) . '</span></button>';
$html .= '<button class="ab-right ab-next-step ab-btn ladda-button" data-style="zoom-in" data-spinner-size="40"><span class="ladda-label">' . Lib\Utils\Common::getTranslatedOption( 'ab_appearance_text_button_next' ) . '</span></button>';
$html .= '</form>';
echo $html;
}
/**
* #return array
*/
public function getProducts()
{
return $this->products;
}
/**
* Add the Product for payment
*
* #param \stdClass $product
*/
public function addProduct( \stdClass $product )
{
$this->products[] = $product;
}
}

Wordpress - How to login user to frontend programmatically

I created function for loging in users on frontend using this example: https://gist.github.com/iandunn/8162246
After user logs in is_user_logged_in() function returns true only inside this function where I placed code for login part.
How do I login users globally?
This is my code:
function programmatic_login( $username ) {
if ( is_user_logged_in() ) {
wp_logout();
}
add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
$user = wp_signon( array( 'user_login' => $username ) );
remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
if ( is_a( $user, 'WP_User' ) ) {
$user_id = $user->ID;
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login );
}
if ( is_user_logged_in() ) {
return true;
}
}
return false;
}
function allow_programmatic_login( $user, $username, $password ) {
return get_user_by( 'login', $username );
}
function process_login(){
// this comes from login form
$username = $_POST["login_username"];
programmatic_login( $username );
// it returns true only here, on any other function it returns false
if(is_user_logged_in()){
echo "ok";
}else{
echo "not ok";
}
}
This is one example where I try to check if user is logged in, outside previous function:
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
function add_login_logout_link($items, $args) {
$loginPage = get_page_by_title("Login");
$registerPage = get_page_by_title("Register");
if(is_user_logged_in()){
$items .= "<li><a href='" . wp_logout_url('index.php') . "' title='Logout'>Logout</a></li>";
}else{
$items .= "<li><a href='". site_url() . '/' . '?page_id=' . $loginPage->ID ."'>Login</a></li><li><a a href='". site_url() . '/' . '?page_id=' . $registerPage->ID ."'>Register</a></li>";
}
return $items;
}
On codex wp_set_current_user there is an example to set the current user and log them in.
$user_id = 12345;
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login );
}
The simplest fix is to use wp_login_form()
see reference: http://codex.wordpress.org/Function_Reference/wp_login_form
If i understand correctly this should handle everything you want.
This will set the auth cookie and can redirect to the page you want, the login works globally

Run plugin code from "functions.php" in WordPress

I have a plugin for allowing duplicate emails on registration and that is working fine if I have used the plugin. I want to use plugin code in functions.php (meaning to say run the plugin code functionality with themes).
Below is my plugin code:
/**
* Plugin Name: Allow duplicate emails on registration
* Plugin URI: http://wordpress.stackexchange.com/a/125129/26350
*/
add_action( 'plugins_loaded', array( 'Allow_Duplicate_Emails_Registration', 'get_instance' ) );
class Allow_Duplicate_Emails_Registratn
{
private $rand = '';
static private $instance = NULL;
static public function get_instance()
{
if ( NULL === self::$instance )
self::$instance = new self;
return self::$instance;
}
public function __construct()
{
// Generate some random string:
$this->rand = '_remove_' . rand( 0, 99999);
add_filter( 'user_registration_email', array( $this, 'user_registration_email' ) );
add_action( 'user_register', array( $this, 'user_register' ) );
}
public function user_registration_email( $user_email )
{
// inject random string into the email
$user_email = str_replace( '#', $this->rand . '#', $user_email );
return $user_email;
}
public function user_register( $user_id )
{
// retrieve the newly registered user object
$user = get_user_by( 'id', $user_id );
// remove the random string
$user_email = str_replace( $this->rand . '#', '#', $user->user_email );
// update the email of the newly registered user
$args = array(
'ID' => $user_id,
'user_email' => $user_email,
);
$result = wp_update_user( $args );
}
}
And I have changed the above code below and put in functions.php, but it is not working:
add_action( 'init', array( 'Allow_Duplicate_Emails_Registration', 'get_instance' ) );
I have solved the problem. Add the below code in the wp-content/themes/my-themes/functions.php file:
<?php
add_filter( 'user_registration_email', array( $this, 'user_registration_email' ) );
add_action( 'user_register', array( $this, 'user_register' ) );
function user_registration_email( $user_email )
{
// Inject a random string into the email
$user_email = str_replace( '#', $this->rand . '#', $user_email );
return $user_email;
}
function user_register( $user_id )
{
// Retrieve the newly registered user object
$user = get_user_by( 'id', $user_id );
// Remove the random string
$user_email = str_replace( $this->rand . '#', '#', $user->user_email );
// Update the email of the newly registered user
$args = array(
'ID' => $user_id,
'user_email' => $user_email,
);
$result = wp_update_user( $args );
}
?>

Resources