Wordpress plugin form submitting to database on every browser refresh - wordpress

I am developing a wordpress plugin, backend is working as I need but I am facing issue in frontend, I have created a shortcode page from I am posting few values to next page but when I refresh the next it is sending values to database again and again. I want to stop it, here is function:
function technician_checklist_report_generated(){
global $current_user;
global $wpdb;
$submit="";
if($_POST['customerid']!=""){
$crow = $wpdb->get_row( 'SELECT customer_id, firstname, lastname, createdon, marina, vesselmodel, vesselname, vesselyear
FROM wp_yacht_customers
WHERE customer_id= '.$_POST['customerid']
);
}
if($crow->customer_id!=""){
$table = 'wp_yatch_vessel_config_checklist';
array_pop($_POST); // delete last element in post array (submit)
$data = $_POST;
$format;
$wpdb->insert( $table, $data, $format );
}
require(dirname(__FILE__) .'/view/technician-start-reporting.php');
}
add_shortcode('technician-start-reporting',
'technician_checklist_report_generated');
When I reach to technician-start-reporting page it is sending data to MySQL again and again on browser refresh.
Is there any other way to go another page because I used wp_redirect and it showing error "header already sent... :

You can only use wp_redirect before content is sent to the browser.
Rather than process the form in the template[insite shortcode], you can hook an earlier action, like wp_loaded (this will be triggered before headers being sent).
<?php
add_action( 'wp_loaded', 'wpv_process_form' );
function wpv_process_form(){
if( isset( $_POST['customerid'] ) ):
// process form, and then
wp_redirect( get_permalink( $pid ) ); // redirect to desired page id
exit();
endif;
}
this way you'll be using less queries too.

Related

Output certain product page on homepage / WooCommerce shortcode not working properly

I need to output a certain product page on the homepage. add_rewrite_rule doesn't work for homepage for any reason (
there are actually no rewrite rules for the homepage in the database, WordPress seems to use some other functions to
query the homepage):
//works fine
add_rewrite_rule( 'certainproductpage/?$',
'index.php?post_type=product&name=certainproduct',
'top'
);
//does not work
add_rewrite_rule( '', //tried everything like "/", "/?$" etc
'index.php?post_type=product&name=certainproduct',
'top'
);
After spending way too much time looking through wp / wc core code and stackoverflow I came across an alternative. I can
simply add a shortcode in the content of the page I need to be the homepage and a product page at the same
time: [product_page id=815]. Indeed it works great, but only if the shortcode is added in the admin editor or is
stored in the database (post_content). If I try to call the shortcode manually on the page template (
page-certainproductpage.php) then it outputs the product page without some necessary stuff (PayPal, PhotoSwipe and
Gallery js). Weirdly enough, if I keep the shortcode in the content (via Gutenberg / Code Editor) but don't
call the_content and only echo the shortcode then everything works fine:
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
get_header( 'shop' );
//works fine only if the same shortcode is within the certainproductpage's content
echo do_shortcode("[product_page id='815']");
//the_content();
get_footer( 'shop' );
Also when I try to add the shortcode via the_content filter hook before the do_shortcode function is applied in core's
default-filters.php ($priority < 11), then I get only the error:
NOTICE: PHP message: PHP Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/html/wp-includes/functions.php on line 5106
Unfortunately there is no stack trace logged. And the function around line 5107 is wp_ob_end_flush_all which is called on shutdown from default-filters.php
echo do_shortcode(apply_filters('the_content', "[product_page id=815]")); did not help either (same incomplete output as
with echo do_shortcode("[product_page id=815]");)
Also totally weird:
When I compare the string of the content from the editor and the string of the shortcode added programmatically it is
equal!:
add_filter( "the_content", function ( $content ){
$wtf = "<!-- wp:paragraph -->
<p>[product_page id=815]</p>
<!-- /wp:paragraph -->";
$result = $wtf === $content;
?><pre><?php var_dump($result)?></pre><?php
return $content;
}, 1 );
But if I replace return $content with return $wtf - I get the maximimum exucution time exceeded error.
So how can I properly output a product page on the homepage ("/") or how can I get the same result with the shortcode
when applied within the the_content filter as when just adding the shortcode in the (Gutenberg) editor?
Update
Tested it with a simple custom shortcode outputting only a heading tag and it works fine with the_content filter. Also tried it on an absolutely clean site with only WooCommerce and PayPal installed - with the same results. Seems to be a bug on the WooCommerce side. Gonna run it through xDebug some day this week.
Ok, found a bit of a hacky solution. I just check on every page load whether the homepage is currently queried or not. Then I get the page content and check if it already contains the shortcode. If not then the page content gets updated in the database with the shortcode appended.
//it has to be a hook which loads everything needed for the wp_update_post function
//but at the same time has not global $post set yet
//if global $post is already set, the "certainproductpage" will load content not modified by the following code
add_action( "wp_loaded", function () {
//check if homepage
//there seems to be no other simple method to check which page is currently queried at this point
if ( $_SERVER["REQUEST_URI"] === "/" ) {
$page = get_post(get_option('page_on_front'));
$product = get_page_by_path( "certainproduct", OBJECT, "product" );
if ( $page && $product ) {
$page_content = $page->post_content;
$product_id = $product->ID;
$shortcode = "[product_page id=$product_id]";
//add shortcode to the database's post_content if not already done
$contains_shortcode = strpos( $page_content, $shortcode ) > - 1;
if ( ! $contains_shortcode ) {
$shortcode_block = <<<EOT
<!-- wp:shortcode -->
{$shortcode}
<!-- /wp:shortcode -->
EOT;
$new_content = $page_content . $shortcode_block;
wp_update_post( array(
'ID' => $page->ID,
'post_content' => $new_content,
'post_status' => "publish"
) );
}
}
}
} );
I'd recommend one step at a time. First of all, does this work?
add_filter( "the_content", function ( $content ) {
$content .= do_shortcode( '[product_page id=815]' );
return $content;
}, 1 );
This should append a product page to every WordPress page/post.
If it works, then you need to limit it to the homepage only, by using is_front_page() conditional in case it's a static page:
add_filter( "the_content", function ( $content ) {
if ( is_front_page() ) {
$content .= do_shortcode( '[product_page id=815]' );
}
return $content;
}, 1 );
If this works too, then we'll see how to return a Gutenberg paragraph block, but not sure why you'd need that, so maybe give us more context

wp_redirect is not saving in functions.php depending on placement

I am adding some code in functions.php (in the wordpress Theme Editor hosted in wp engine) and depending on where I place wp_redirect, it will save or not save
Example: It will save when I do this
add_action('template_redirect','test_template');
//this one saves fine
function test_template() {
global $wp_query;
$userId = $wp_query->get( 'userId', NULL );
$url = get_site_url();
if ( NULL !== $userId ) {
wp_redirect($url);
exit;
}
}
//However, when I do this I get: "Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP."
function test_template() {
global $wp_query;
$userId = $wp_query->get( 'userId', NULL );
$url = get_site_url();
wp_redirect($url);
exit;
}
Not sure why the second function will not save, any ideas?
The second one is triggering a infinite redirect loop. According to WordPress Codex: https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect
This action hook executes just before WordPress determines which template page to load
This means that it will run every time before loading a page template. So basicaly after wp_redirect($url) the action template_redirect will be hooked and will redirect again.

Send custom refereal code to registration in WordPress

I'm passing a referral code that I'm saving to wp_usertmeta with a custom field added in functions.php
So far, so good!
Link to wp register: wp-login.php?action=register&ref=2
I save the referral code with:
<?php $ref = $_GET['ref']?>
It works BUT, if i enter a username thats already taken i get the standard error message from WordPress that it's taken.
When this happens the URL reloads to: wp-login.php?action=register and i cant use $_GET['ref']
Is there any alternative way to do this?
The easiest way to solve this would be to save the $_GET['ref'] value to a cookie or the PHP session. Once the user is registered, you can refer to the cookie/session to save to the database using the user_register action hook. Once it is saved, you should clear this value if it is a cookie unless it is needed for something else to reduce the size of each request.
//set the cookie
if ( isset( $_GET['ref'] ) ){
setcookie( "ref", $_GET['ref'] );
}
Then save the value using the action hook
add_action( 'user_register', 'my_user_register' );
function my_user_register( $user_id ){
if ( isset( $_COOKIE['ref'] ) ){
// save the ref to the user meta
update_user_meta( $user_id, 'ref', $_COOKIE['ref'] );
// delete the cookie
setcookie( "ref", null, -1 );
}
}

Wordpress hook to authenticate user for pre-defined URLs

I'm building a fairly complex project that has many frontend editing pages. For example, add/edit/list custom post types, edit profile, and so on, all from the frontend.
At the moment I can of course check if user is logged in on each frontend login-walled page. However, this seems like a bad way of solving this problem as I'll have the same conditional on many pages and thus lots of repeated code.
I was thinking perhaps there is a better way where I could authenticate based on some hook (that I can't finds). I hoped I could do something like:
# create array of URLs where login is required
$needLoginArr = array(url1, url2, url3, ...)
# If current requested URL is in above array, then redirect or show different view based on whether or not user is logged in
It might not be practical in future to have conditional on each page as I plan on integrating within different plugins, so would be useful to use URL to authenticate.
I'm probably missing something here so if there's a better way please let me know.
Thanks
You could add your list of page IDs into an option:
$need_login = array(
'page1',
'page1/subpage',
'page2',
// and so forth
);
$need_login_ids = array();
foreach( $need_login as $p ) {
$pg = get_page_by_path( $p );
$need_login_ids[] = $pg->ID;
}
update_option( 'xyz_need_login', $need_login_ids );
Then, to check if your page is in the $need_login group:
add_filter( 'the_content', 'so20221037_authenticate' );
function so20221037_authenticate( $content ) {
global $post;
$need_login_ids = get_option( 'xyz_need_login' );
if( is_array( $need_login_ids ) && in_array( $post->ID, $need_login_ids ) ) {
if( is_user_logged_in() ) {
// alter the content as needs
$content = 'Stuff for logged-in users' . $content;
}
}
return $content;
}
References
get_page_by_path()
is_user_logged_in()
update_option()
get_option()

How can I add/update post meta in a admin menu page?

I wanted to create a plugin to batch manage posts' custom field data. I know I can add post meta by adding a meta box in the post edit screen and using add_action('save_post', 'function_to_update_meta') to trigger add meta functions.
But I don't know how to trigger the add_post_meta function in an admin menu page (such as a custom admin menu). How to do that?
Thank you in advance!
The example given in Wordpress' codex is probably the best and most secure in the way of processing information:
Add Meta Box
Copy and paste it and then fiddle around with it to get a good idea on how to control your posts and pages.
The nice part is that you don't need to worry about checking if you need to Add vs Update a given Post Meta field. Using Update Post Meta will ensure that the proper action is taken for you, even if the field doesn't exist.
The same goes for Update Option if you want to add some global controls that your plugin/theme might use.
BREAKDOWN EXAMPLE:
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
These are the action hooks. The first one is executed when meta boxes are being populated within the post editor, and the second is executed when a post is added OR updated.
function myplugin_add_custom_box()
{
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'page'
);
}
This function is called by the 'add_meta_boxes' action hook. Notice the name of the function and the second argument of the action hook are exactly the same. This registers your meta boxes, which post types they're supposed to appear, and what callback is used to generate the form contained inside.
function myplugin_inner_custom_box( $post )
{
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
$value = get_post_meta($post->ID, 'myplugin_new_field') ? get_post_meta($post->ID, 'myplugin_new_field') : 'New Field';
echo '<label for="myplugin_new_field">';
_e("Description for this field", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.$value.'" size="25" />';
}
This is the function that is called by the registered meta boxes to generate the form automatically. Notice how the function is called 'myplugin_inner_custom_box' and the 3rd argument in your meta box registration is also called 'myplugin_inner_custom_box'.
The wp_nonce_field() generates a hidden field in your form to verify that data being sent to the form actually came from Wordpress, and can also be used to end the function in case other plugins are using the 'save_post' action hook.
Notice also that the $post object is being passed in as an argument. This will allow you to use certain properties from the post object. I've taken the liberty of checking to see if there is get_post_meta() returns anything with the given post ID. If so, the field is filled with that value. If not, it is filled with 'New Field'.
function myplugin_save_postdata( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = $_POST['myplugin_new_field'];
update_post_meta($post_id, 'myplugin_new_field', $mydata);
}
This is the function that is called by the 'save_post' action hook. Notice how the second argument of the second action hook and this function are both called 'myplugin_save_postdata'. First, there are a series of verifications our plugin must pass before it can actually save any data.
First, we don't want our meta boxes to update every time the given post is auto-updating. If the post is auto-updating, cancel the process.
Secondly, we want to make sure the nonce data is available and verify it. If no nonce data is available or is not verified, cancel the process.
Thirdly, we want to make sure the given user has the edit_page permission. The function first checks the post type, and then checks the appropriate permission. If the user does not have that permission, cancel the process.
Lastly, our plugin has finally been verified and we want to save the information. I took the liberty of adding in the final update_post_meta() line to show you how it all comes together.
Notice how $post_id was passed into the function as an argument. This is one of the pieces needed for the update_post_meta() function. The key was named 'myplugin_new_field' and the value of that metadata is now saved as whatever you input into that custom input field in your custom meta box.
That's about as easy as I can explain the whole process. Just study it, and get your hands dirty with code. The best way to learn is through application rather than theory.
The answer was from the same question I asked somewhere else
And I created my version of example
I added some console.log function for testing, but this is basically doning the same thing as #Chris_() answer:
Menu callback function to generate menu content (PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, 'your_key', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
Then the javascript to print on the admin side (javascript, don't forget to include a jquery library):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log('Submit Function');
var postMeta = $('input[name="1"]').val();
console.log(postMeta);
var postID = 1;
var button = $('input[type="submit"]');
button.val('saving......');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: 'POST',
url: ajaxurl,
success: function( response ) { console.log('Well Done and got this from sever: ' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
Then the PHP function handle update_post_meta (PHP):
add_action( 'wp_ajax_update_meta', 'my_ajax_callback' );
function my_ajax_callback() {
$post_id = $_POST['post_id'];
$post_meta = $_POST['post_meta'];
update_post_meta( $post_id, 'your_key', $post_meta );
echo 'Meta Updated';
die();
} // end of my_ajax_callback()

Resources