I have created a plugin for wordpress that show a form to users by shortcode, i want submit the form ,get the values and store in defined table that created when my plugin is activated.
Now i don't know where this form should be submit. I define a submenu for plugin in admin panel (and set form action to this submenu slug) to get that value and store in db, but only those how logged in can submit that form.
You can handle any form submission using template_redirect hook if your form is in the frontend. If your form in the backend then you can use admin_init hook
Say, Your form code looks like in front end
<form method="post">
<input type="text" name="input_1"/>
<input type="number" name="input_2"/>
<?php wp_nonce_field( 'name_of_your_nonce_action', 'name_of_your_nonce_field' ) ?>
<input type="submit" name="submit_form" value="Submit" />
</form>
Now in theme functions.php file, you can handle this form like
<?php
add_action( 'template_redirect', 'wp1213_handle_custom_form', 11 );
function wp1213_handle_custom_form() {
if( ! isset( $_POST['submit_form'] ) ) {
return;
}
if( ! wp_verify_nonce( $_POST['name_of_your_nonce_field'], 'name_of_your_nonce_action' ) ) {
return;
}
// Then you can handle all post data ($_POST) and save those data in db
.......
}
Related
So I'm trying to follow this tutorial but what I want to do is a bit different.
I want to have a unique link per coupon generator and the coupon is per customer and can only be used once (e.g. example.com/coupon/7AD8679adO).
Now I want to have a form for this page and just have a input boxes for users like first_name, last_name, and email. And the email field is the identifier that the current url coupon will be registered to that email.
I also tried to research and I found out that there's URL Coupons feature from Woocommerce (Not sure though if this is exactly what Im looking for), but suddenly, it is not free. So, any idea with this?
I have implemented rewrite rule in "twentytwentyone" theme, but you may implement it elsewhere in wordpress.
For more info, please refer to this.
https://developer.wordpress.org/reference/functions/add_rewrite_rule/
Implement in wordpress Theme
Add the following code to the bottom of next file
~/wp-content/themes/twentytwentyone/functions.php
// wp-content/themes/twentytwentyone/functions.php
...
// rewrite-rule
add_action( 'init', function() {
add_rewrite_rule( 'coupon/([a-zA-Z0-9]+)[/]?$', 'index.php?coupon=$matches[1]', 'top' );
} );
// whitelist "coupon" param
add_filter( 'query_vars', function( $query_vars ) {
$query_vars[] = 'coupon';
return $query_vars;
} );
// set template php file
add_action( 'template_include', function( $template ) {
if ( get_query_var( 'coupon' ) == false || get_query_var( 'coupon' ) == '' ) {
return $template;
}
//You can return wherever you want to go
return get_template_directory() . '/template-coupon.php';
} );
Create ~/wp-content/themes/twentytwentyone/template-coupon.php
// wp-content/themes/twentytwentyone/template-coupon.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo get_query_var( 'coupon' )." from POST".PHP_EOL;
var_dump($_POST);
// check coupon validation here
// $query = $wpdb->prepare("SELECT 1"); // Your query
// $result = $wpdb->get_var($query);
// var_dump($result);
} else {
echo get_query_var( 'coupon' )." from redirection GET".PHP_EOL;
// do something
}
?>
<?php //get_template_part( 'header' ); ?>
<form action="" method="POST">
<label for="first_name">First Name</label><input type="text" name="first_name" id="first_name"><br/>
<label for="last_name">Last Name</label><input type="text" name="last_name" id="last_name"><br/>
<label for="email">Email</label><input type="text" name="email" id="email"><br/>
<input type="submit">
</form>
<?php //get_template_part( 'footer' ); ?>
Implement in wordpress Plugin (Hello Dolly)
Add the above step 1 code to the bottom of next file
~/wp-content/plugins/hello.php
change
return get_template_directory() . '/template-coupon.php';
to
return __DIR__ . '/template-coupon.php';
Add the above step 2 code to ~/wp-content/plugins/template-coupon.php
Refresh permalinks cache
When you add/modify URL part in step1, you need to refresh permalniks cache, otherwise wordress does not apply rewrite rule.
Settings > Permalinks > Save Changes
Result
check http://your-domain/coupon/7AD8679adO/
I'm pretty sure you've seen this answer elsewhere, but I hope this is written clearly enough for you to understand it better.
It seems as though you may need to implement the "add_rewrite_rule()" in order for WordPress to recognise the element (the unique "/coupon/URL") and pass on the resulting code to the right page.
Additionally, it can sometimes be a bit more difficult to verify a coupon code without the user being logged into an account that can be relied on.
Therefore, I would recommend trying to store the uniquely generated "/coupon/URL" in the user's meta data, and then querying for the unique in the user's meta data, and validating the request if the current user and the related user's ID match. This is because the code doesn't just get tied to the email address, but also to a registered user.
I know there will be this type of questions but i have tried almost all options without luck so i'm asking here.
I have issue that cart is not empty in woocommerce after order completed and also some users just add items to cart then not go to checkout and after somedays come back again they still see old cart.
I think it may be caching issue as i'm using W3-total-cache plugin.
I want to clear cart data after checkout or if user add items to cart and not checkout and after a while come back again for shopping then cart must be empty and should not store old session to cart.
I tried below code but no luck :
function nom_empty_cart_init_login(){
$opt = get_option('nom_empty_cart_browser_close_do_login');
$opt = $opt != 1 ? false : true;
if( $opt ){
session_destroy();
}
}
// destroy session on user logout
function nom_empty_cart_init_logout(){
$opt = get_option('nom_empty_cart_browser_close_do_logout');
$opt = $opt != 1 ? false : true;
if( $opt ){
session_destroy();
}
}
add_action('admin_menu','nom_empty_cart_init_admin_init');
function nom_empty_cart_init_admin_init(){
add_options_page( 'Woocommerce Clear Cart on Browser Closing', 'WC Clear Cart on Browser Close', 'manage_options', 'wc-clear-cart-on-browser-close', 'wc_clear_cart_on_browser_close' );
}
function wc_clear_cart_on_browser_close(){
if( isset( $_REQUEST['save_accconc'] ) and wp_verify_nonce($_REQUEST['wc-clear-cart-on-browser-close-name'],'wc-clear-cart-on-browser-close-action')):
// SAVING THE FORM DATA
// enable wcccobc
if( isset($_REQUEST['enable_wcccobc']) )
update_option('nom_empty_cart_browser_close_enable',1);
// enable wcccobc on login
if( isset($_REQUEST['enable_wcccobc_on_login']) )
update_option('nom_empty_cart_browser_close_do_login',1);
// enable wcccobc on logout
if( isset($_REQUEST['enable_wcccobc_on_logout']) )
update_option('nom_empty_cart_browser_close_do_logout',1);
// SAVING ;) ENDS
endif;
?>
<div class="wrap">
<div class="inside">
<h2>Woocommerce Clear Cart on Browser Closing</h2>
<p>Note: the cart will be empty if the visitor close the whole browser, not just the widow. (will be updated soon)</p>
<form action="<?php admin_url('options-general.php?page=wc-clear-cart-on-browser-close');?>" method="post">
<?php wp_nonce_field('wc-clear-cart-on-browser-close-action','wc-clear-cart-on-browser-close-name')?>
<p>
<input id="enable_wcccobc" type="checkbox" class="checkbox" name="enable_wcccobc" value="1" <?php checked(get_option('nom_empty_cart_browser_close_enable'),'1');?>>
<label for="enable_wcccobc" >Enable clear cart on browser closing</label>
</p>
<p>
<input id="enable_wcccobc_on_login" type="checkbox" class="checkbox" name="enable_wcccobc_on_login" value="1" <?php checked(get_option('nom_empty_cart_browser_close_do_login'),1);?>>
<label for="enable_wcccobc_on_login" >Enable clear cart on on user login</label>
</p>
<p>
<input id="enable_wcccobc_on_logout" type="checkbox" class="checkbox" name="enable_wcccobc_on_logout" value="1" <?php checked(get_option('nom_empty_cart_browser_close_do_logout'),1);?>>
<label for="enable_wcccobc_on_logout">Enable clear cart on user logout</label>
</p>
<p>
<input type="submit" class="button-primary" value="Save" name="save_accconc">
</p>
</form>
</div>
</div>
<?php
}
I'm using method from #shoelaced and it work.
edit on theme's functions.php
add_action( 'woocommerce_payment_complete', 'order_received_empty_cart_action', 10, 1 );
function order_received_empty_cart_action( $order_id ){
WC()->cart->empty_cart();
}
i did prevent all user are not admin from wp-admin with this code
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) &&
! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit();
}
}
and i created frontend login form with wp_signon(); the problem is when i submit form in admin account it's successfully logged in but when trying access wp-admin it always return to home page url
so what's wrong and how can i fix this problem
my form
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['logingo']) && $_POST['logingo']=='logingo'){
global $user;
$creds = array();
$username = (isset($_POST['login_name'])) ? $_POST['login_name'] : '';
$password = (isset($_POST['login_password'])) ? $_POST['login_password'] : '';
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$userid = wp_signon($creds,false);
if(is_wp_error($user)){
$proccess = '<div class="error_msg">'.$user->get_error_message().'</div>';
$_SESSION['logged_errors'] = $proccess;
}
if(!is_wp_error($userid)){
$_SESSION['logged_success'] = 'success message';
wp_redirect(get_author_posts_url($userid->ID));
exit();
}
}
?>
<form action="" method="post">
<label class="login_name">
<input type="text" value="" name="login_name" required />
</label>
<label class="user_password">
<input type="password" name="login_password" required />
</label>
<button type="submit" name="logingo" value="logingo">go</button>
</form>
This may be a result of the following issues:
Code Snippet that redirects to homepage in wp-login.php: post the code of your login page in the question.
Cookie problem: Clear your browser cookies and cache, restart your browser and try login
Plugin: Have you activated a login plugin? Or maybe its another plugin that is causing issues. Deactivate all plugins and see if succesful.
Theme issue: maybe there is something wrong with your theme. Change to default theme and install your desired theme afresh. Hook your Access-Limit code to functions.php
I recommend you use a pre-built plugin to limit access to WordPress dashboard for non-admin users, if not create your own plugin. Changing code in functions.php is not advisable see here
This quick snippet will force WordPress to redirect to the URL that you specify in wp_redirect() when a user fails to login. We also append a $_GET variable, login, and set it equal to failed, which we can use in our theme to display special content only when the user has failed to login.
add_action( 'wp_login_failed', 'pippin_login_fail' ); // hook failed login
function pippin_login_fail( $username ) {
$referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from?
// if there's a valid referrer, and it's not the default log-in screen
if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
wp_redirect(home_url() . '/?login=failed' ); // let's append some information (login=failed) to the URL for the theme to use
exit;
}
}
question regarding Woocommerce payment gateways.
I’ve customized a payment gateway to take purchase orders, and its loading correctly from a plugin, and appearing on the checkout page the way id like it to; I think its a pretty good start.
Anyway, I have a non-standard form entry (purchase order number) that id like people to fill out, but I don’t know how to attach it to my custom payment gateway so that it appears on the resulting admin side page.
This all works fine:
function payment_fields(){
if ( $description = $this->get_description() )
echo wpautop( wptexturize( $description ) );
global $woocommerce;
?>
<form class="form-horizontal" role="form" id="bv-form">
<fieldset>
<!-- Form Name -->
<legend>Purchase Order</legend>
<!-- Text input-->
<div class="form-group">
<label class="control-label" for="po_no">PO Number</label>
<div class="">
<input id="po_no" name="po_no" type="text" placeholder="" class="form-control input-md">
</div>
</div>
...
But when I get here, I don’t know how to modify process_payment( $order_id ) (or what to add to functions.php) to grab the form values from the payment fields. I see that there are $order->billingAddress1 etc., how would I submit the extra couple form fields along with the order, and then secondly, how would I access that to get po_no out of the newly created WC_Order?
WP: 3.9.2
WC: 2.1.11
Thanks for your help!
If you are creating a custom Payment Gateway then you should be implementing process_payment() within it. This code will have access to the $_POST variables were submitted by the payment form, so you can refer to it as:
$po_number = ( isset( $_POST['po_no'] ) )? $_POST['po_no'] : 0;
That said it sounds like from your question you may not be actually writing a custom gateway and are instead trying to attach custom fields to the order. If you want to hook into another gateway (like PayPal, Authorize.net, etc) then you should use the WooCommerce action hooks that are called as part of WC_Order.payment_complete() which is what the gateway calls after it collects payment. The actions are woocommerce_pre_payment_complete which runs before anything else and takes the order id as an argument, and woocommerce_payment_complete after stock/statuses/etc are set.
add_action( 'woocommerce_payment_complete', 'my_woocommerce_payment_complete');
function my_woocommerce_payment_complete( $order_id ){
$po_number = ( isset( $_POST['po_no'] ) )? $_POST['po_no'] : 0;
update_post_meta( $order_id, 'po_number', $po_number );
}
You can then display this custom field on the Order Edit page by adding a meta box. You'll need to hook into save_post and change the po_number to an input if you want to make it editable.
add_action( 'add_meta_boxes', 'po_number_metabox' );
function add_po_number_metabox(){
global $post;
if ( $post->post_type = 'shop_order' ){
add_meta_box( 'po-number', 'Title', 'po_number_metabox', 'shop_order', 'side', 'default');
}
}
function po_number_metabox(){
global $post;
$po_number = get_post_meta( $post->ID, 'po_number', true);
echo "PO:> {$po_number}";
}
WordPress 3.2.1
I'm creating separate page templates, however, there are some page templates that should have default custom fields. That is, if someone created a new page of template type "Contact Us", it should by default have custom fields:
Success Message
Email To
Phone Number
etc.
Right now, the only way I can think of knocking this out is by having the admin add those custom fields to the page, and then fill them in. However, this isn't the best method for basically giving an admin a "turn-key" type of feature, i.e., they create a page with a specific template and just fill in the fields.
Thanks guys!
The following will add 1 extra meta box to your (insert-edit) page.
In it you can add custom fields to save.
It does not switch depending on the selected template.
I would recomend using javascript to show/hide fields to do this. Based on ID of the <p>
If you get the meta box working with ALL possible fields you can show I'm willing to help with the javascript to hide and show based on the template.
GL
<?php
add_action( 'add_meta_boxes', 'carrousel_build' );
function carrousel_build()
{
add_meta_box('carrousel', 'Carrousel opties', 'carrousel_options', 'page',/*show on 'pages'*/ 'normal', 'high');
}
//this will add a meta box with custom fields
function carrousel_options ($post)
{ ?>
<p>
Description
</p>
<p id="field1_container">
<label for="field1">Custom field 1</label>
<br/>
<input type="text" id="field1" name="field1" value="<?php echo get_post_meta($post->ID, 'field1', true) ?>" size="25" />
</p>
<p id="field2_container">
<label for="field2">Custom field 2</label>
<br/>
<input type="text" id="field2" name="field2" value="<?php echo get_post_meta($post->ID, 'field2', true) ?>" size="25" />
</p>
<?php }
//save the values of the meta box
add_action( 'save_post', 'post_save' );
function post_save($post_id)
{
// Check permissions
if (isset ($_POST['post_type']) && 'carrousel' == $_POST['post_type'] && !current_user_can( 'edit_page', $post_id ))
{
return;
}
if (isset($_POST['field1'])) {
$subtitle = $_POST['field1'];
update_post_meta($post_id, 'field1', $subtitle);
}
if (isset($_POST['field2']))
{
$link = $_POST['field2'];
update_post_meta($post_id, 'field2', $link);
}
}