Writing Woocommerce product data to downloadable CSV - csv

I'm trying to write the product details from a woocommerce product page to a downloadable CSV, on the click of a button.
Similar structure to this:
<?php
$header_args = array( 'SKU', 'Description', 'Price' );
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=csv_export.csv');
$output = fopen( 'php://output', 'w' );
ob_end_clean();
fputcsv($output, $header_args);
$data = array(
'0' => array( '$product->get_sku();', '$product->get_description();', '$product->get_price();' ),
);
foreach($data AS $data_item){
fputcsv($output, $data_item);
}
exit;
?>
Can someone assist on how I can alter this code? so on a button click or link click, a CSV will download with SKU, Description & Price?

Related

cURL retrieve json data and store in mysql database from url

i'm facing problems into cURL. here i can get the json data from another source code and also i got some ideas. but really i can't save the json data into my own server in sql database. i wanna to retrieve the data from
url: https://jamuna.tv/wp-json/wp/v2/posts
and wanna to save into my server (mysql).
here is the $url json data i wanna to save in mysql server:
id
date
link
title
content
author
categories
wp:attachment
and i want to save them into mysql database. my table name is "news" and i want to save them into my table columns.
id [id]
title [title]
description [content]
date [date]
category [categories]
thumbnail [wp:attachment]
admin [author]
here i'm mark the json from url and replaced into my sql columns name. if anyone can give me the instructions about how i can fetch the data from user and save into mysql.
thanks advance.
There is an implementation of your desired with PHP. You must check if values are valid or not or if the array members exist or not. This is just a primitive implementation of your example.
<!DOCTYPE html>
<html>
<body>
<?php
// db connection
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO('mysql:host=localhost;dbname=test;', 'user', 'pass', $options);
// download json from url
$json = file_get_contents('https://jamuna.tv/wp-json/wp/v2/posts');
echo '<br/>';
$sql = "INSERT INTO `mytable` (`id`,`title`,`description`,`date`,`category`,`thumbnail`,`admin`)
VALUES (:id, :title, :content , :date, :categories, :attachment, :author)";
$stm = $db->prepare($sql);
// parse JSON
$arr = json_decode($json, true);
$i = 0;
foreach ($arr as $record) {
echo "==================Insert record " . $i ++ . "<br>";
$data = array(
':id' => $record['id'],
':title' => $record['title']['rendered'],
':content' => $record['content']['rendered'],
':date' => $record['date'],
':categories' => $record['categories'][0],
':attachment' => $record['_links']['wp:attachment'][0]['href'],
':author' => $record['author']
);
var_dump($data);
// inserting a record
$stm->execute($data);
}
?>
</body>
</html>

How to parse php inside html

I tried to parse the php query into html, but on the html page it shows array.
My query looks like this: $comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve') );
I tried to print it on the html page using this: $html .= $comments;
As you can see from the examples.
And as Tom J Nowell commented, you need to loop through each comment and append the comment to the $html.
$args = array(
'status' => 'approve',
'post_id' => $post->ID,
);
$comments = get_comments( $args );
foreach ( $comments as $comment ) :
$html .= $comment->comment_author . '<br />' . $comment->comment_content . '<br />';
endforeach;

mysql query different meta_key and display them separately

I am a new to mysql and my question is difficult for me to describe. Wordpress stores a lot of postmeta as various meta_keys that contain various meta_values. I'm having a problem trying to query by a particular meta_key but and then being able to display 2 different meta_keys and their values. Here is what I have so far which properly displays all of the video urls from a particular wordpress category...
<?php
$myquery=mysql_query("
SELECT * FROM foy_postmeta AS pm
INNER JOIN foy_term_relationships AS tr ON (pm.post_id = tr.object_id)
INNER JOIN foy_posts AS p ON (pm.post_id = p.ID)
WHERE pm.meta_key='video_url'
AND tr.term_taxonomy_id='27'
AND p.post_status='publish'
ORDER BY p.post_date DESC
");
$rows = array();
while($row=mysql_fetch_array($myquery)){
$rows[] = $row;
}
?>
And then I put this into rows within my html which properly displays all of the video titles and their paths...
<?php
foreach( $rows as $row ) {
<div>my video title: <?php echo $row["post_title"]; ?></div>
<div>my video url: <?php echo $row["meta_value"]; ?></div>
}
?>
Now, what I would like to do is to keep this same row list, but to also write out another meta_key and it's value, something like this....
<?php
foreach( $rows as $row ) {
<div>my video title: <?php echo $row["post_title"]; ?></div>
<div>my video url: <?php echo $row["meta_value"]; ?></div>
<div>my video format is: <?php echo $row["meta_value"]; ?></div>
}
?>
But I'm not sure how I can display 2 meta_values within the same loop since they have separate meta_keys within the same postmeta table.
you can use wp_query for this. Its the wordpress database query for posts which makes things easier when dealing with post_meta.
http://codex.wordpress.org/Class_Reference/WP_Query
for example for the above
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'video_url',
)
),
'tax_query' => array(
array(
'taxonomy' => 'your taxonomy name here',
'field' => 'slug',
'terms' => 'whatever'
)
),
'orderby' => 'date',
'order' => 'DESC',
);
$query= new wp_query($args);
?>
while ( $query->have_posts() ) : $query->the_post();
$meta = get_post_meta( $post->ID );
var_dump($meta);
?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
now for every post you can access the post_meta (check what the array var_dumps for the keys)
or if you want to persist with mysql use a foreach loop for each row and pass the id to get_post_meta($id); you can then use the postmeta for every row.
I found a solution that although works, I'm thinking there is a better way to do it. I removed the specific meta_key item within the query so that I could grab all meta_keys, and then used if statements within the foreach loop to create variables of the particular ones I wanted to display:
<?php
$myquery=mysql_query("
SELECT * FROM foy_postmeta AS pm
INNER JOIN foy_term_relationships AS tr ON (pm.post_id = tr.object_id)
INNER JOIN foy_posts AS p ON (pm.post_id = p.ID)
WHERE tr.term_taxonomy_id='27'
AND p.post_status='publish'
ORDER BY p.post_date DESC
");
$rows = array();
while($row=mysql_fetch_array($myquery)){
$rows[] = $row;
}
<?php
foreach( $rows as $row ) {
// sets video url and video layout values as variables
if ($row["meta_key"] == "video_url" ){ $videourl = $row["meta_value"]; }
if ($row["meta_key"] == "video_layout" ){ $videolayout = $row["meta_value"]; }
if ($row["meta_key"] == "video_url" ){
?>
<div>my video url: <?php echo $videourl ?></div>
<div>my video format is: <?php echo $videolayout ?></div>
<?php
}
}
?>

Move Wordpress Custom Post Type Content to a Custom Field Value

Hey all I have a 163 posts imported into a custom post type from a csv file, it's all great except one little problem. The plugin forced me to put a column into the content field - so I chose one that I was going to put as a custom field - is there anyway for me to now convert all of them into a custom field and clear the content area?
Thanks!
You could put something like this (untested) in functions.php
add_action( 'get_header', 'so19967768_update_posts' );
function so19967768_update_posts()
{
if( ! isset( $_GET['update'] ) )
return;
$posts = get_posts( array( 'post_type' => 'my_post_type', 'posts_per_page' => -1 ) );
foreach( $posts as $post )
{
setup_postdata( $post );
$value = $post->post_content;
update_post_meta( $post->ID, 'my_meta_key', $value );
wp_update_post( array(
'ID' => $post->ID,
'post_content' => ''
) );
}
echo 'update complete!';
die();
}
and visit yoursite.com/?update=1 to run the update

How to get all metavalue for a specific custom field for all posts in one category?

I'm trying to get the sum for all the meta values of one custom field. I now get the sum for the metavalues of the whole site. I want it to be restricted to the category you're in.
The code now looks like this:
<?php
$thevariable = $wpdb->get_var($wpdb->prepare("
SELECT SUM($wpdb->postmeta.meta_value)
FROM $wpdb->postmeta, $wpdb->posts
WHERE $wpdb->postmeta.meta_key='mycustomfield'
AND $wpdb->postmeta.post_id=$wpdb->posts.id
"));
echo '<h1>' . $thevariable . '</h1>';
?>
Can somebody help me to filter out one category?
Would be amazing!
M
Inside your WP files, you can add this lines; I guess It will do what you are looking for.
<?php
$MySum = 0;
$args = array(
'category_name' => 'MyCategory',
'meta_key' => 'mycustomfield',
'posts_per_page' => '-1' );
// The Query
$the_query = new WP_Query( $args);
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
$MySum += get_post_meta($post_id, $key, true);
endwhile;
echo '<h1>' . $MySum . '</h1>';
// Reset Post Data
wp_reset_postdata();
?>