Save CSV Export to Server - php

I have the code below which triggers when a button is pressed in the WordPress admin panel. This opens a csv file called 'ss-stock-export.csv'.
How can I save this file to my server in my uploads directory at wp-content/uploads/exports/? I tried to use file_put_contents but that doesn't seem to be working right. The CSV file appears in the right spot but it is blank. Possibly something wrong with my $output?
<?php
function generate_stock_report_csv() {
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
// set file name with current date
header('Content-Disposition: attachment; filename=ss-stock-export.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// set the column headers for the csv
$headings = array( 'sku', 'qty', 'is_in_stock' );
// output the column headings
fputcsv($output, $headings );
// get all simple products where stock is managed
// get all product variations where stock is managed
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_stock',
'value' => array('', false, null),
'compare' => 'NOT IN'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$product = new WC_Product_Variation( $loop->post->ID );
$ss_sku = get_post_meta( $product->variation_id, 'ss_sku', true);
$stock = $product->stock;
settype($stock, "integer");
if ($stock > 0){ $stock_status = 1;} else {$stock_status = 0;}
$row = array( $ss_sku , $product->stock, $stock_status );
fputcsv($output, $row);
endwhile;
$filename = "ss-stock-export.csv"; // Trying to save file in server
file_put_contents(ABSPATH . "wp-content/uploads/exports/" . $filename, $output);
} ?>

You can use the ABSPATH constant defined in wp-config.php to pass an absolute path to file_put_contents. That way it doesn't matter where you're running the script from.
file_put_contents(ABSPATH . "wp-content/uploads/exports/" . $filename, $output);

This did the trick
$csv = "sku,qty,is_in_stock \n";//Column headers
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_stock',
'value' => array('', false, null),
'compare' => 'NOT IN'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$product = new WC_Product_Variation( $loop->post->ID );
$ss_sku = get_post_meta( $product->variation_id, 'ss_sku', true);
$stock = $product->stock;
settype($stock, "integer");
if ($stock > 0){ $stock_status = 1;} else {$stock_status = 0;}
$row = array( $ss_sku , $product->stock, $stock_status );
$row_array= array($row);
foreach ($row_array as $record){
$csv.= $record[0].','.$record[1].','.$record[2]."\n"; //Append data to csv
}
endwhile;
$csv_handler = fopen ('ss-stock-export.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
file_put_contents(ABSPATH . "wp-content/uploads/exports/ss-stock-export.csv", $csv);
}

Related

How to export category name and category link in wordpress json

all queries work except category name and category link, if I use "get_the_category()" it shows several things I don't need, like "category_count" , "category_description" etc.
and i need to know how to separate jsons by post category
this is my code
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
$posts = array();
while( $query->have_posts() ) : $query->the_post();
$posts[] = array(
'id' => get_the_ID(),
'date' => get_the_date(),
'title' => get_the_title(),
'link' => get_the_permalink(),
'image' => get_the_post_thumbnail_url(),
'category' => get_the_category ( 'cat_name' ),
'categoryLink' => get_category_link ( $category_id )
);
endwhile;
wp_reset_query();
$data = json_encode($posts);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen( $save_path , "w" );
fwrite($f , $data);
fclose($f);
}
add_action( 'save_post', 'export_posts_in_json' ); ```
get_the_category requires a post id (or boolean false) - See: https://developer.wordpress.org/reference/functions/get_the_category/
get_category_link requires an integer or category object - See: https://developer.wordpress.org/reference/functions/get_category_link/
Check your parameters and see if that helps.

Filter WooCommerce related products by Polylang language

I'm using polylang plugin to having multi-languages website.
Using WooCommerce with polylang demands duplicating each product for each language, so assuming I have Hebrew and English, that means 2 duplications for each products.
It works fine with WooCommerce plugin, but when I'm displaying "related products" at the end of the product page, it's mixing products in English and Hebrew together.
I expect to filter the related product by website current language (if(get_locale() == 'en_US') - to check website current locale state, else will represent Hebrew).
Polylang functions
Here is what I have tried, but I got stuck on the part of filtering the product by language:
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
How can I filter Woocommerce related product section by language?
Edit
So after a little bit of research and help in the comments I found out that 'lang' => 'en' argument does exist, but even when I use it, there is no change on related products language display.
Any ideas?
add_filter( 'woocommerce_product_related_posts', 'custom_related_products' );
function custom_related_products($product){
global $woocommerce;
// Meta query
$meta_query = array();
$meta_query[] = $woocommerce->query->visibility_meta_query();
$meta_query[] = $woocommerce->query->stock_status_meta_query();
$meta_query = array_filter( $meta_query );
// Get the posts
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'fields' => 'ids',
'meta_query' => $meta_query,
'suppress_filters' => false
) );
if ( $related_posts->have_posts() ) {
while ( $related_posts->have_posts() ) : $related_posts->the_post();
if(pll_get_post_language(get_the_ID())){
//Not sure its the right approach for this..
}
endwhile;
}
$related_posts = array_diff( $related_posts, array( $product->id ), $product->get_upsells() );
return $related_posts;
}
suppress_filters There is a way to make get_posts cache the results however, the suppress_filters option is true by default, but if you set it to false, the caching mechanisms inside WordPress will do their work, and results will be saved for later.
You can try this code:
$related_posts = get_posts( array(
'orderby' => 'rand',
'posts_per_page' => '4',
'post_type' => 'product',
'meta_query' => $meta_query,
'lang' => 'en'
) );
if ($related_posts) {
foreach ($related_posts as $post) {
setup_postdata($post);
// something like <li><?php the_title(); ?></li>
}
}
wp_reset_postdata();
This code correctly returns code in selected language on my site
While working on a custom WordPress REST Api end point to fetch post by selected language or device language, this worked. See if it can help you out.
function mycustomplugin_posts($params) {
// get the url params
$page = $params->get_param('page') ? $params->get_param('page') : 0;
$per_page = $params->get_param('per_page') ? $params->get_param('per_page') : 10;
$offset = $params->get_param('offset') ? $params->get_param('offset') : 0;
$order = $params->get_param('order') ? $params->get_param('order') : 'desc';
$order_by = $params->get_param('order_by') ? $params->get_param('order_by') : 'date';
$lang = array_search($params->get_param('lang'),polylang_json_api_languages(), true) ? $params->get_param('lang') : pll_default_language();
$args = [
'post_type' => 'post',
'page' => $page,
'numberposts' => $per_page,
'offset' => $offset,
'order' => $order,
'orderby' => $order_by,
'tax_query' => [
[
'taxonomy' => 'language',
'field' => 'slug',
'terms' => $lang
]
]
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
// Extract the post data
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['excerpt'] = e42_the_short_content($post->post_content, 300);
$data[$i]['slug'] = $post->post_name;
$data[$i]['date'] = $post->post_date;
$data[$i]['link'] = get_permalink($post->ID);
$data[$i]['author'] = get_the_author_meta('display_name', $post->post_author);
$data[$i]['categories'] = array();
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
foreach(get_the_category($post->ID) as $category){
array_push($data[$i]['categories'],$category->term_id);
}
$i++;
}
// Create the response object
$response = new WP_REST_Response( $data );
// Add a custom status code
$response->set_status( 200 );
return $response;
}
/plugins/woocommerce/templates/single-product/related.php
Move this to child theme
yourtheme/woocommerce/single-product/related.php
And add the following line to the foreach loop
if (pll_current_language()!=pll_get_post_language($post_object->ID)) {
continue;
}
Basically if current language does not match product language we skip over it.

Wordpress search and Filter API for IOS and Android

I am working on a project to apply filters on wordpress post...I have created JSON Output and Now I need to apply 5 filters that are as follows..
1. All
2. Today
3. WeekEnd
4. Next Seven Days
5. Date wise
Flow of the whole process...GEt Posts data in JSON--> Fetch This Data --> Create Filters---> User can Then Search as well as filter Data Further with normal wordpress functions....But I am not able to work out for fetching out posts by applying the Next Seven days filter and weekEnd..as the issue seems to be at my way of fetching the posts...What I am doing for now is
Code for Next Seven Days or last seven days...
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
//require_once("config.php" );
require_once("incformfunctions.php");
if($_SERVER['REQUEST_METHOD'] == "GET"){
$numberposts = isset($_REQUEST['numberposts']) ? $_REQUEST['numberposts'] : "-1";
$posttype = isset($_REQUEST['posttype']) ? $_REQUEST['posttype'] : "";
$securitycode = $_REQUEST['securitycode'];
$mode = $_REQUEST['mode']? $_REQUEST['mode'] : "ALL";
$taxonomy='art_categories';
if($securitycode == $secret)
{
$category_data=array();
if($mode=='recommended') //to get recommended post of posttype category
{
$args= array(
'numberposts' => 100,
'category' => 0,
'orderby' => 'date',
'order' => 'DESC',
'include' => array(),
'exclude' => array(),
'meta_key' => '',
'meta_value' =>'',
'post_type' => 'events', //post name
'suppress_filters' => true,
'date_query' => array(
array(
'key' => 'event_start_date', //custom name start date
'after' => '1 week ago'
),
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_editors_choice', //custom name event editor
'value' => true
),
'relation' => 'AND',
array(
'key' => 'event_recommended', //custom name event recommended
'value' => true
),
),
);
}
$myposts = get_posts( $args); // get all value in array
if($myposts) {
foreach ( $myposts as $post ) : setup_postdata( $post ); //and using foreach loop show all post type field
$image= get_the_post_thumbnail_url();
$featured_image =wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ));
$start_date= get_post_meta($post->ID,'event_start_date',true);
$start_date=date('F j, Y', strtotime($start_date));
$end_date = get_field('event_end_date', $post->ID, false);
$end_date=date('F j, Y', strtotime($end_date));
$event_type = get_field('event_type', $post->ID, true);
$event_venue = get_field('event_venue', $post->ID, true);
$event_venue_address = get_field('event_venue_address', $post->ID, true);
$latitude = get_field('event_venue_latitute', $post->ID, true);
$longitude = get_field('event_venue_longitude', $post->ID, true);
$description_long = get_field('event_description_long', $post->ID, true);
$description_short = get_field('event_description_short', $post->ID,
true);
$gallery_address = get_field('gallery_address', $post->ID,
true);
if($gallery_address==false)
{
$gallery_address="";
}
$event_gallery = get_post_meta($post->ID,'gallery_address', true);
$venue_address= get_field('venue_address',$event_gallery,true);
$venue_postcode= get_field('venue_postcode',$event_gallery,true);
$venue_city= get_field('venue_city',$event_gallery,true);
$venue_location= get_field('venue_location',$event_gallery,true);
if($venue_location==false)
{
$venue_location="";
}
$venue=get_post_custom($post->ID);
$category=get_the_category($post->ID); //category
$excerpt=get_the_excerpt( $post );
$posttypes=get_post_type( $post );
$category_data[] = array('id' => get_the_ID (),'title' => get_the_title(),'excerpt' =>$excerpt,'featured_image' =>$featured_image,'image' =>$image,'event_type' =>$event_type,'event_venue' =>$event_venue,'event_venue_address' =>$event_venue_address,'event_latitude' =>$latitude,'event_longitude' =>$longitude,'start_date' =>$start_date,'end_date' =>$end_date,'posttypes' =>$posttypes,'tags'=>$tags,'description_long'=>$description_long,'description_short'=>$description_short,'venue'=>$event_gallery,'gallery_address'=>$gallery_address,'venue_address'=>$venue_address,'venue_postcode'=>$venue_postcode,'venue_city'=>$venue_city,'venue_location'=>$venue_location); // getting in all post array formate
wp_reset_postdata();
endforeach;
$data = $category_data;
$errcode=100;
$errstr='success';
}
else {
$errcode=-1;
$errstr='Post not found please check again..';
}
}
//for securitycheck
if ($securitycode !=$secret or $securitycode=='')
{
$errstr="unauthorise access";
}//end
}
else{
$errcode=-2;
$errstr='Request method not accepted';
}
#mysql_close($conn);
/ Output header /
#header('Content-type: application/json');
echo json_encode(array('errcode'=>$errcode,'errstr'=>$errstr,'data'=>$data)); // json create
die();
Any Help on what I am doing wrong??

Get images by a slug in Wordpress

I am fairly new to Wordpress and I am trying to make a function that loads images under a media category. The media category has a slug that I want to pass into the function. If there is an easier way to do this please let me know. Below is my code so far:
Functions.php
function get_image_by_slug($slug) {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' =>'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'attachment_category',
'field' => 'slug',
'terms' => $slug,
),
),
);
$query_images = new WP_Query( $query_images_args );
$images = array();
foreach ( $query_images->posts as $image) {
$images[]= $image->guid;
}
return $images;
}
function display_image_by_slug() {
$imgs = get_image_by_slug($slug);
$html = '<ul class="list-inline">';
foreach($imgs as $img) {
$html .= '<li><img src="' . $img . '" alt="" /></li>';
}
$html .= '</ul>';
return $html;
}
add_filter('display_slugs','display_image_by_slug');
In page
<?php apply_filter('display slugs', 'test_slug');?>
An attachment of image or file is just a post with the post_status = inherit and the post_type = attachment and it is saved into the wp_post & wp_postmeta , so can be queried with WP_Query or get_posts.
Note: The slug (post_name) is unique per post type.
You have to pass your slug in the query by replacing YOUR-SLUG in this place. &name=YOUR-SLUG
$_head = get_posts('post_type=attachment&name=YOUR-SLUG&posts_per_page=1&post_status=inherit');
$header = $_head ? array_pop($_head) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : '';
Another Method you can build your own custom function with the help that i have provided below.
function get_attachment_url_by_slug( $slug ) {
$args = array(
'post_type' => 'attachment',
'name' => sanitize_title($slug),
'posts_per_page' => 1,
'post_status' => 'inherit',
);
$_head = get_posts( $args );
$header = $_head ? array_pop($_head) : null;
return $header ? wp_get_attachment_url($header->ID) : '';
and then you can call using this function.
$header_url = get_attachment_url_by_slug('YOUR-SLUG');
So after looking around the Wordpress docs and understanding Naresh's answer I was able to come up with my own answer. Here it is...
$id = 'YOUR SLUG';
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'media_category', // your taxonomy
'field' => 'slug',
'terms' => $id // term id (id of the media category)
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>'. wp_get_attachment_image( get_the_ID() );
if(empty_content(get_the_content())){
echo '<p>' . get_the_excerpt() . '</p></li>';
} else {
echo '<p>'.get_the_excerpt().'</p></li>';
}
}
} else {
// no attachments found
}
wp_reset_postdata();

Show the variation label (Woocommerce)

I'm using this slightly modified script (inside a loop) which helps me generate two links which I use to add products to the cart:
<?php
// Get the ID of the product
$id = $_POST["post_var"];
// Get variations
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'publish' ),
'numberposts' => 2,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => $product->id
);
$variations = get_posts( $args );
$loop = 0;
if ( $variations ) {
foreach ( $variations as $variation ) {
$formats[$loop]["id"] = absint( $variation->ID );
$formats[$loop]["data"] = get_post_meta( $variation->ID );
$variation_label = "?????????";
$loop++;
}
foreach ( $formats as $type )
$response .= '' . $variation_label . '';
} ?>
<?php echo $response; ?>
The only thing I can't figure out is how to get the variation labels.
Every product has variation called "Format' with the options "Electronic" and "Physical" and I need those to be output into the link. So the $response would look something like this:
<a href="http://example.com/checkout?add-to-cart=93&variation_id=94&quantity=1&attribute_pa_format=Electronic">Electronic</a
Physical
You can see I've added a variable called $variation_label as a placeholder.
Stumped.

Categories