I have some custom code and I am not sure how to catch that Post request.
<?php $nonce = wp_create_nonce('nrc_update_certifications_nonce');?>
<?php $link = admin_url('admin-ajax.php?action=nrc_update_certifications&nonce=' . $nonce); ?>
<file-upload
extensions="jpg,jpeg,png,pdf"
:accept="accept"
:multiple="true"
post-action="<?php echo $link;?>"
:data="{
types: accept,
certifications_ids: certifications_ids,
}"
v-model="certifications"
name="certifications[]"
#input-filter="inputFilter"
ref="upload">
<span class="button">Select files</span>
</file-upload>
In my child theme I have a file update-certifications.php. This file is imported in functions.php
function nrc_update_certifications() {
// I don't get here!
if ( !wp_verify_nonce( $_REQUEST['nonce'], "nrc_update_certifications_nonce")) {
exit("No naughty business please");
}
exit ("Works!");
}
add_action('wp_ajax_update_certifications', 'nrc_update_certifications');
The correct way to do that is the following:
function nrc_update_certifications() {
// I don't get here!
if ( !wp_verify_nonce( $_REQUEST['nonce'], "nrc_update_certifications_nonce")) {
exit("No naughty business please");
}
exit ("Works!");
}
add_action('wp_ajax_nrc_update_certifications', 'nrc_update_certifications');
What changes is that when you do add_action the action starts with "wp_ajax_" and it MUST be followed by what you specify in the action parameter of your call.
Since you build the link like this:
<?php $link = admin_url('admin-ajax.php?action=nrc_update_certifications&nonce=' . $nonce); ?>
Then the missing part after wp_ajax_ must be "nrc_update_certifications". What you are free to change is the function specified as the second parameter of add_action
Sidenote: if you want that ajax to be available for non-logged user aswell, then you are missing another call to add action which should be:
add_action( 'wp_ajax_nopriv_nrc_update_certifications', 'nrc_update_certifications' );
See the "nopriv" part of the action.
If you want to know more i suggest you to take a look at this: https://codex.wordpress.org/AJAX_in_Plugins
Related
I created a new page in my admin panel.
On this page, for example function is_admin() works fine.
if ( ! is_admin() ) {
echo "You are viewing the theme";
} else {
echo "You are viewing the WordPress Administration Panels";
}
From this page i send post data to xxx.php file.
And! In this xxx.php file functions such as is_admin doens't work.
How can i let wordpress to understand, that this xxx.php file is the part of him? So i can use functions on this page?
I am using
"include wp-load.php"
but it doesn't help me.
You can add him in the theme folder & include in functions.php:
// functions.php of your current theme
include __DIR__.'/custom.php';
I just checked the source code on Github.
function is_admin() appears in this file https://github.com/WordPress/WordPress/blob/6fda2e67b0fe3872cbf5f82b58b98f2a4c96d8f8/wp-includes/load.php#L710-L717
So, require_once 'wp-includes/load.php; should sort you out.
The fact that you're sending POST data (request, i assume) to another php file makes me think that it's a completely different HTTP request, therefore you won't be able to use wp functions in the target php file, unless you include wp-load.ph in that file.
See this: https://wordpress.stackexchange.com/questions/69184/how-to-load-wordpress-on-non-wp-page
add_action('admin_menu', function(){
add_menu_page( 'Subscribe', 'Subscribe', 'manage_options', 'subsc-options', 'sub_setting', '', 4 );
} );
add_action( 'current_screen', function( $current_screen ){ // hook is admin panel only
if ( stripos($current_screen->base, 'subsc-options')==true ) {
include __DIR__.'/custom.php';
}
});
<form method="post">
<input type="hidden" name="my_save_settings" >
..............
</form>
/********* CUSTOM.PHP **************/
if ( isset($_POST['my_save_settings']) ) {
// save form fields
}
I am trying to add a custom URL structure to a WordPress based website.
for example:
example.com/machines //list all machines in a table
example.com/machines?some=params //list filtered machines in a table
example.com/machines/1 //show single machine
The data will come from an external api i have already developed, via curl.
I cannot import the data into a custom post type as it is normalized over many tables, the business logic is complicated and the api is used by other devices anyway.
I have looked at the docs for add_rewrite_rule, but the second parameter has me stumped:
$redirect
(string) (required) The URL you would like to actually fetch
Well I don't have a url to fetch, I want to run a function, that will act as a simple router - take the url parts, call the external api and return a template with the correct data.
Calling the API will be simple, but how i actually route the url to the function, and how I then load a template (utilizing existing WordPress header.php and footer.php) has me stumped.
After much googling and reading a few good resources, I have found the solution.
Step 1: Use add_rewrite_endpoint to create a base url that will be mapped to a query variable:
add_action( 'init', function(){
add_rewrite_endpoint( 'machines', EP_ROOT );
} );
Step 2: Visit the permalinks settings page and click "Save Changes" to flush the rewrite rules.
Step 3: Hook into the action 'template_redirect' to actually do something when the url is hit:
add_action( 'template_redirect', function() {
if ( $machinesUrl = get_query_var( 'machines' ) ) {
// var_dump($machinesUrl, $_GET);
// $machinesURl contains the url part after example.com/machines
// e.g. if url is example.com/machines/some/thing/else
// then $machinesUrl == 'some/thing/else'
// and params can be retrieved via $_GET
// after parsing url and calling api, it's just a matter of loading a template:
locate_template( 'singe-machine.php', TRUE, TRUE );
// then stop processing
die();
}
});
Step 4: The only other thing to do is handle a hit to a url with no further parts to it e.g. example.com/machines.
It turns out that at some point within WordPress's guts, the empty string gets evaluated to false and thus skipped, so the final step is to hook into the filter 'request' and set a default value:
add_filter( 'request', function( $vars = [] ) {
if ( isset( $vars['machines'] ) && empty( $vars['machines'] ) ) {
$vars['machines'] = 'default';
}
return $vars;
});
This can easily be improved by wrapping it all in a class(es).
The url parsing and template loading logic can be passed to a basic router, even a rudimentary MVC setup, loading routes from a file etc, but the above is the starting point.
A simplier solution is to just create a new template redirect.
So assuming you loading example.com/custom-url
/**
* Process the requests that comes to custom url.
*/
function process_request() {
// Check if we're on the correct url
global $wp;
$current_slug = add_query_arg( array(), $wp->request );
if($current_slug !== 'custom-url') {
return false;
}
// Check if it's a valid request.
$nonce = filter_input(INPUT_GET, '_wpnonce', FILTER_SANITIZE_STRING);
if ( ! wp_verify_nonce( $nonce, 'NONCE_KEY')) {
die( __( 'Security check', 'textdomain' ) );
}
// Do your stuff here
//
die('Process completed' );
}
add_action( 'template_redirect', 'process_request', 0);
I am facing an issue with Contact Form 7 for Wordpress. I want to disable the email notification which i did using
demo_mode: on
At the same time i want to redirect on submit which i used to do using
on_sent_ok: "location = 'http://domain.com/about-us/';"
Both would work when used individually.But i want to use both at the same time.
I tried doing
on_sent_ok: "location = 'http://domain.com/about-us/';"
demo_mode: on
Doesnt seem to work. Kindly advice.
The plugin author has changed as of at least 4.0 the way you should do this again. The skip_mail property is now private :
class WPCF7_Submission {
private $skip_mail = false;
...
}
You should use this filter : wpcf7_skip_mail
For example :
function my_skip_mail($f){
$submission = WPCF7_Submission::get_instance();
if(/* YOUR TEST HERE */){
return true; // DO NOT SEND E-MAIL
}
}
add_filter('wpcf7_skip_mail','my_skip_mail');
The author of the plugin Contact Form 7 has refactored some of the code for its version 3.9 and since then the callback function for the hook wpcf7_before_send_mail must be written differently.
To prevent Contact Form 7 from sending the email and force it to redirect after the form has been submitted, please have a look at the following piece of code (for version >= 3.9):
add_action( 'wpcf7_before_send_mail', wpcf7_disablEmailAndRedirect );
function wpcf7_disablEmailAndRedirect( $cf7 ) {
// get the contact form object
$wpcf7 = WPCF7_ContactForm::get_current();
// do not send the email
$wpcf7->skip_mail = true;
// redirect after the form has been submitted
$wpcf7->set_properties( array(
'additional_settings' => "on_sent_ok: \"location.replace('http://example.com//');\"",
) );
}
Hook into wpcf7_before_send_mail instead of using the flag .
add_action("wpcf7_before_send_mail", "wpcf7_disablemail");
function wpcf7_disablemail(&$wpcf7_data) {
// this is just to show you $wpcf7_data and see all the stored data ..!
var_dump($wpcf7_data); // disable this line
// If you want to skip mailing the data..
$wpcf7_data->skip_mail = true;
}
Just an update. The following works in 4.1.1.
on_sent_ok: "location = 'http://domain.com/about-us/';"
demo_mode: on
Set skip_mail: on does the trick.
There might have been a change to contact-form-7, because I wasn't able to access the $skip_mail variable in the WPCF7_Submission object. I looked at the submission.php object in the \wp-content\plugins\contact-form-7\includes\submission.php file and found this:
private $skip_mail = false;
Since the variable is private, and there are no getters or setters in the file, you're not going to be able to change it externally. Just change it to this:
public $skip_mail = false;
and then you can change the variable like this in your functions.php file:
add_filter('wpcf7_before_send_mail', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url( $form)
{
$submission = WPCF7_Submission::get_instance();
$submission->skip_mail = true;
}
A reminder, if you update the contact-form-7 plugin, it will probably nullify your change, so keep that in mind.
Simple code
Copy and paste the following code in your activated theme functions.php file.
add_filter('wpcf7_skip_mail','__return_true');
UPDATE WPCF7 ver. 7.5: There is now a filter specifically to handle this.
function my_skip_mail($f){
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
if (/* do your testing here*/){
return true; // DO NOT SEND E-MAIL
}
}
add_filter('wpcf7_skip_mail','my_skip_mail');
I have installed SMS Validator so everyone who register to my site must enter there phone number to sign-up
Now I have created a new function (link) to add a different type user role if users sign-up by visit this link:
http://example.com/wp-login.php?action=register&role=vip_member
I want to turn OFF SMS Validator ONLY for this URL link.
Is it possible to do it somehow?
Success so far using mathielo code:
// Activate SMSGlobal
function activate_plugin_conditional() {
if ( !is_plugin_active('sms-validator-SMSG/sms-validator.php') ) {
activate_plugins('sms-validator-SMSG/sms-validator.php');
}
}
// Deactivate SMSGlobal
function deactivate_plugin_conditional() {
if ( is_plugin_active('sms-validator-SMSG/sms-validator.php') ) {
deactivate_plugins('sms-validator-SMSG/sms-validator.php');
}
}
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=vip_member') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=seller') !== FALSE){
// Calls the enable function at WP's init
add_action( 'init', 'activate_plugin_conditional' );
}
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=provider') !== FALSE){
// Calls the enable function at WP's init
add_action( 'init', 'activate_plugin_conditional' );
}
So far this code helps me to activate and deactivate this plugin in this 3 selected URLs.
But I want this plugin to be activated if is deactivated in this links: /wp-login.php and /wp-login.php?action=register
But if I set it to activate on URL: /wp-login.php then it will not be deactivated on URL: /wp-login.php?action=register&role=vip_member where I need it to be deactivated.
You could match the current URL using $_SERVER["REQUEST_URI"] and then disable the plugin in functions.php:
// Just creating the function that will deactivate the plugin
function deactivate_plugin_conditional() {
if ( is_plugin_active('plugin-folder/plugin-name.php') ) {
deactivate_plugins('plugin-folder/plugin-name.php');
}
}
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], 'my-disable-url') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
Note: Be aware that php's strpos() may return 0 if the needle matches the given string at position zero, so the condiional !== is needed.
Got my references from here and implemented the URL check. Check out the current value of $_SERVER["REQUEST_URI"] at your desired URL for a perfect match.
Answering the second part of your question:
You could improve your code removing the last 2 ifs and complementing the first one with an else, like so:
// Now you in fact deactivate the plugin if the current URL matches your desired URL
if(strpos($_SERVER["REQUEST_URI"], '/wp-login.php?action=register&role=vip_member') !== FALSE){
// Calls the disable function at WP's init
add_action( 'init', 'deactivate_plugin_conditional' );
}
// Otherwise, for any other URLs the plugin is activated if it's currently disabled.
else{
add_action( 'init', 'activate_plugin_conditional' );
}
Now for every URL that is not the one you wish to deactivate the plugin, your code will enable the plugin if it is currently inactive.
I have url like this http://localhost/join/prog/ex.php
When i use GET method the url address like this http://localhost/join/prog/ex.php?name=MEMORY+2+GB&price=20&quantity=2&code=1&search=add
My question is :
so, I still use the GET method but I want to after processing in GET method is finished, I want to the url back(remove parameter) into http://localhost/join/prog/ex.php, as previously (not using POST method). How can i do it?
Put this in your HTML file (HTML5).
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", "http://localhost/join/prog/ex.php");
}
</script>
Or using a backend solution using a session for instance;
<?php
session_start();
if (!empty($_GET)) {
$_SESSION['got'] = $_GET;
header('Location: http://localhost/join/prog/ex.php');
die;
} else{
if (!empty($_SESSION['got'])) {
$_GET = $_SESSION['got'];
unset($_SESSION['got']);
}
//use the $_GET vars here..
}
SIMPLE ANSWER
Just place this in the top of the file you need to make the GET querys disappear from the browser's URL bar after loading.
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", '<?php echo $_SERVER['PHP_SELF'];?>');
}
</script>
i guess after calling the url you want to redirect to the file ex.php , but this time without any parameters.
for that try using the following code in ex.php
<?
if($_GET['name']!='' || $_GET['price']!='' ||$_GET['quantity']!='' ||$_GET['code']!='' || $_GET['search']!=''){
/* here the code checks whether the url contains any parameters or not, if yes it will execute parameters stuffs and it will get redirected to the page http://localhost/join/prog/ex.php without any parameters*/
/* do what ever you wish to do, when the parameters are present. */
echo $name;
print $price;
//etc....
$location="http://localhost/join/prog/ex.php";
echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">';
exit;
}
else{
/* here rest of the body i.e the codes to be executed after redirecting or without parameters.*/
echo "Hi no parameters present!";
}
?>
here what u did id just redirect redirect to the same page without checking if any parameter is there in the query string. the code intelligently checks for the presence of parameters, id any parameters are there it will redirect to ex.php else it will print "Hi no parameters present!" string!
If you're using apache, consider using a .htaccess file with mod_rewirte.
Here a quickstart. I think this result can be obtained on iis as well with web.config file
You can use removable_query_args filter for that.
add_filter( 'removable_query_args', function( $vars ) {
$vars[] = 'name';
$vars[] = 'price';
$vars[] = 'quantity';
$vars[] = 'code';
$vars[] = 'search';
return $vars;
} );
But you should add specific conditions for your case, otherwise, it will remove these Get-parameters from all other URLs on your site as well.
More info here