I have this code which is meant to take woocommerce product data (from single product page) and export it to a downloadable CSV on button click, but whenever I click the button it just refreshes the page?
<?php
// Define the function to export a WooCommerce product to CSV
function export_product_to_csv() {
// Get the product ID from the URL parameter
$product_id = $_GET['product_id'];
// Get the product data from the database
$product = wc_get_product($product_id);
// Create the CSV file
$csv_file = fopen('product.csv', 'w');
// Write the header row to the CSV file
fputcsv($csv_file, array('Product Name', 'SKU', 'Price', 'Stock Status'));
// Write the product data to the CSV file
fputcsv($csv_file, array($product->get_name(), $product->get_sku(), $product->get_price(), $product->get_stock_status()));
// Close the CSV file
fclose($csv_file);
// Download the CSV file
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="product.csv";');
readfile('product.csv');
exit;
}
// Check if the export button was clicked
if (isset($_POST['export'])) {
export_product_to_csv();
}
?>
<!-- Add the export button to the WooCommerce product page -->
<form method="post">
<input type="hidden" name="product_id" value="<?php echo get_the_ID(); ?>">
<button type="submit" name="export">Export to CSV</button>
</form>
Related
Im working on a simple script to include a "Add to calendar" button.
Im using the idea and ICS.php file from https://gist.github.com/jakebellacera/635416 that is a old post.
Im getting the file to download through a function using add_action( 'template_redirect', 'cl_download_ics' ); [The theme is Avada]. But what is happening now is that the download invite is including the themes template file to the file that I don't want and even after removing the template code that was added extra the file still does not want to add the event to the iCalendar.
Here is the code I have so var.
include_once (plugin_dir_path(__DIR__).'cl-add-to-calendar/ics.php');
function cl_download_ics(){
if (isset( $_GET['ics'])) {
$query_data_get = $_POST;
//$query_data = $query_data_get['calendar_data'];
$dtstart = date_create($query_data_get['date_start']);
$dtstart = date_format($dtstart,"Y/m/d H:i:s");
$dtend = date_create($query_data_get['date_end']);
$dtend = date_format($dtend,"Y/m/d H:i:s");
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=Invite.ics');
$ics = new ICS(array(
'location' => $query_data_get['location'],
'description' => $query_data_get['description'],
'dtstart' => $dtstart,
'dtend' => $dtend,
'summary' => $query_data_get['summary'],
'url' => $query_data_get['url']
));
echo $ics->to_string();
}
}
add_action( 'template_redirect', 'cl_download_ics' );
function calendar_btn_ad($atts){
// Shortcode atts with examples
// dtsrart --- 2017-1-16 9:00AM
// dtend --- 2017-1-16 9:00AM
// location --- 123 Fake St, New York, NY
// description --- This is my description
// summary --- This is my summary
// url --- http://example.com
$form_input_fields = array();
if (! empty($atts['dtsrart'])) {
$form_input_fields[] = '<input type="hidden" name="date_start" value="'.$atts['dtsrart'].'">';
};
if (! empty($atts['dtend'])) {
$form_input_fields[] = '<input type="hidden" name="date_end" value="'.$atts['dtend'].'">';
};
if (! empty($atts['location'])) {
$form_input_fields[] = '<input type="hidden" name="location" value="'.$atts['location'].'">';
};
if (! empty($atts['description'])) {
$form_input_fields[] = '<input type="hidden" name="description" value="'.$atts['description'].'">';
};
if (! empty($atts['summary'])) {
$form_input_fields[] = '<input type="hidden" name="summary" value="'.$atts['summary'].'">';
};
if (! empty($atts['url'])) {
$form_input_fields[] = '<input type="hidden" name="url" value="'.$atts['url'].'">';
};
$download_link = WP_PLUGIN_URL.'/cl-add-to-calendar/download-ics.php';
ob_start();
?>
<form action="?ics=true" method="post">
<?php foreach ($form_input_fields as $input_field): ?>
<?php echo $input_field; ?>
<?php endforeach; ?>
<input type="submit" id="cl-add-calendar-submit" value="Add to Calendar">
</form>
<div id="cl-btn-ajax-result">
</div>
<?php
$output = ob_get_clean();
return $output;
}
add_shortcode('cl_calendar_btn', 'calendar_btn_ad');
It is a feed, so add the feed using wordpress add_feed and your function. see
https://developer.wordpress.org/reference/functions/add_feed/.
function add_custom_feed() {
add_feed( 'ics', 'cl_download_ics' );
}
add_action( 'init', 'add_custom_feed' );
function cl_download_ics() {
header('Content-Type: text/calendar; charset=utf-8');
etc.....
}
I'm using custom post types for the event and adding the ics feed when I register the post type. Adding the feed needs to be done with an early wordpress action. Don't use theme actions.
I'm trying to fetch the WooCommerce products meta data using $product = new WC_Product( get_the_ID() ); I'm getting the product price and all the other values the products are downloadable WooCommerce products, I want to fetch the following data:
Whenever i try to fetch $product->downloads->id or $product->downloads->file i'm getting null in return. Please tell me what i'm doing wrong over here.
To access all product downloads from a downloadable product you will use WC_Product get_downloads() method.
It will give you an array of WC_Product_Download Objects which protected properties are accessible through WC_Product_Download available methods (since WooCommerce 3):
// Optional - Get the WC_Product object from the product ID
$product = wc_get_product( $product_id );
$output = []; // Initializing
if ( $product->is_downloadable() ) {
// Loop through WC_Product_Download objects
foreach( $product->get_downloads() as $key_download_id => $download ) {
## Using WC_Product_Download methods (since WooCommerce 3)
$download_name = $download->get_name(); // File label name
$download_link = $download->get_file(); // File Url
$download_id = $download->get_id(); // File Id (same as $key_download_id)
$download_type = $download->get_file_type(); // File type
$download_ext = $download->get_file_extension(); // File extension
## Using array properties (backward compatibility with previous WooCommerce versions)
// $download_name = $download['name']; // File label name
// $download_link = $download['file']; // File Url
// $download_id = $download['id']; // File Id (same as $key_download_id)
$output[$download_id] = ''.$download_name.'';
}
// Output example
echo implode('<br>', $output);
}
Related answers:
Add downloads in Woocommerce downloadable product programmatically
Add programmatically a downloadable file to Woocommerce products
If you're trying to get the download link, try:
$downloads = $product->get_downloads();
This should return an array, so you can use it for example like:
foreach( $downloads as $key => $download ) {
echo 'Download File';
}
How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>
Dear Fellow PhP Experts,
I am writing below code to export HTML table data in PHP.
Its working nicely in localhost. However, when I deployed to the domain, there is warning-
'Warning: Cannot modify header information - headers already sent by
(output started at ../result_month.php:64 //dbconnect.php line//) in
../result_month.php on line 77 //header("Location: $FileName") line//'.
Seeking suggestion from you, what I am exactly doing wrong.
<?php require_once('dbconnect.php'); ?>
<?php
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
?>
<?php //I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
Any content without PHP open tag are treated as HTML, sent as HTTP_BODY.
HTTP_BODY will be sent after HTTP_HEADER was closed.
Try these codes:
<?php
require_once('dbconnect.php');
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
//I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
// WARNING : Uncomment this will cause header() call failed.
//echo "THIS IS HTTP_BODY";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
I have made a script with a form which is supposed to submit a persons email to a .txt file, only problem is that nothing happends to the .txt file, it is kept blank when the function is called. Both the html file and the php file is kept in the same folder and the .txt file is named formdata.txt .
Html code:
<form name="newsletter-form" action="process-form-data.php" method="post" id="newsletter-form">
<input type="email" name="newsletter-email" id="newsletter-email" class="form-control" placeholder="Enter Your Email" data-validate="validate(required, email)" />
<input type="submit" id="newsletter-submit" class="btn" value="Notify Me" />
</form>
Php code named process-form-data.php:
<?php
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email : '.$email.'
=========================
';
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
?>
Your code works for me.
Here's a variation using file_put_contents:
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
//$email = 'myhappymail#unhappy.com';
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email2! : '.$email.'
=========================
';
file_put_contents( $filename, $f_data, FILE_APPEND | LOCK_EX );
// $file = fopen($filename, "a");
// fwrite($file,$f_data);
// fclose($file);
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
Do a:
var_dump( $_POST );
die;
at the top of your script. I'm thinking you're missing your POST data.