wp_insert_post generating duplicate id - wordpress

I use following code to generate id for a product variation.
$i = 0;
while($i < 2){ // 2 is example
$product = wc_get_product($product_id);
$variation_post = array(
'post_title' => 'Variation #' . $i . ' of ' . $product->get_name(),
'post_name' => 'product-'.$product_id.'-variation',
'post_status' => 'publish',
'post_parent' => $product_id,
'post_type' => 'product_variation',
'guid' => $product->get_permalink()
);
if((post_exists('Variation #' . $i . ' of ' . $product->get_name())) == 0){
$variation_id = wp_insert_post( $variation_post );
}
$variation = new WC_Product_Variation( $variation_id );
$i++;
}
but the wp_insert_post generating two ids instead one . I use this code in ajax file,
where is the problem?!

Related

How To Filter and Display ONLY Simple WooCommerce Products using Shortcode

I have a functional shortcode that outputs all products. Problem is, I need this to only "find" simple products.
add_shortcode('product_list', 'simple_product_list');
function simple_list_shortcode() {
$query = new WP_Query( array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'hide_empty' => 0,
'orderby' => 'title',
'post_id' => 'id'));
$output = '<ul style="list-style-type:none">';
while ( $query->have_posts() ) : $query->the_post();
$product = wc_get_product($query->post->ID);
$price = $product->get_regular_price();
$output .= '<li>' . $query->post->post_title . ' costs '.wc_price($price) . ', <a class="atc" href="'. $product->add_to_cart_url() .'">order now</a>.</li>';
endwhile;
wp_reset_postdata();
return $output.'</ul>';
}
Since it is already using 'post_type' => 'product', I cannot add another with simple.
I tried using a if statement for ->is_type('simple'), but doing so turned the page white and nothing is displayed.
Your shortcode callback function and your actual function name is different.
You can get product type using $product->get_type() function.
UPDATE 1: Using WP_Query().
add_shortcode('product_list', 'simple_list_shortcode');
function simple_list_shortcode()
{
ob_start();
$query = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish',
'hide_empty' => 0,
'orderby' => 'title',
'post_id' => 'id'
));
$output = '<ul style="list-style-type:none">';
while ($query->have_posts()) : $query->the_post();
$product = wc_get_product($query->post->ID);
if($product->get_type() == 'simple'){
$price = $product->get_regular_price();
$output .= '<li>' . $query->post->post_title . ' costs ' . wc_price($price) . ', <a class="atc" href="' . $product->add_to_cart_url() . '">order now</a>.</li>';
}
endwhile;
wp_reset_postdata();
echo $output . '</ul>';
$contents = ob_get_clean();
return $contents;
}
UPDATE 2: you can also use wc_get_products() function to get products with arguments.
add_shortcode('product_list', 'simple_product_list');
function simple_product_list()
{
$arg = array(
'type' => 'simple',
'orderby' => 'date',
'order' => 'DESC',
) ;
$products = wc_get_products($arg);
ob_start();
$output = '<ul style="list-style-type:none">';
foreach( $products as $product){
$price = $product->get_regular_price();
$output .= '<li>' . $product->get_name() . ' costs ' . wc_price($price) . ', <a class="atc" href="' . $product->add_to_cart_url() . '">order now</a>.</li>';
}
echo $output . '</ul>';
$contents = ob_get_clean();
return $contents;
}

How to get order info from 'my accounts > orders' page in Woocommerce? $order->get_id() does not match the order number

WordPress, WooCommerce, I am logged in and have purchased an order. The order number is 61. I have written some code to add a button that will email the admin to let them know I am requesting a refund for this order. Problem is that the order number I get back does not match that shown. I am new to coding so I am sure the error will be obvious to someone else. Could use your insight.
Here is my code. For testing, I am just displaying the values above the button.
$Customer = $order->get_billing_first_name() . " " . $order->get_billing_last_name();
$orderno = $order->get_id();
foreach ( $order->get_items() as $item_id => $item ) {
$Product = $item->get_name();
$pid = $order->get_id();
$Amount = $order->get_formatted_order_total( );
$status = $order->get_status();
}
echo 'Customer: ' . $Customer . ' Order: ' . $orderno . ' Product: ' . $Product . " Order#" . $pid . ' Amount: ' . $Amount . " status: " . $status;
$customer = wp_get_current_user();
// Get all customer orders
$customer_orders = get_posts(array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'orderby' => 'date',
'order' => 'DESC',
'meta_value' => get_current_user_id(), // login user
'post_type' => wc_get_order_types(),
'post_status' => array_keys(wc_get_order_statuses()),
'post_status' => array('wc-processing'), // order status
));
$Order_Array = []; //
foreach ($customer_orders as $customer_order) {
$orderq = wc_get_order($customer_order);
$Order_Array[] = [
'ID' => $orderq->get_id(), //order id
'Value' => $orderq->get_total(), // order value
'Date' => $orderq->get_date_created()->date_i18n('Y-m-d'), //order date
];
}

Display Product Count in WooCommerce category with subcategory

How to display total number of product in category with subcategory in WooCommerce?
I'm try using this code, but it work perfectly only in categories without subcategory.
add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 10);
function add_product_count_view() {
global $wp_query;
$category_id = $wp_query->get_queried_object()->term_id;
$term = get_term( $category_id, 'product_cat' );
echo $term->name . '(' . $term->count . ')';
}
Paste this code in function.php:
add_action( 'count_product_title', 'add_product_count_view', 10);
function add_product_count_view() {
global $wp_query;
$category_id = $wp_query->get_queried_object()->term_id;
//echo sprintf( _n( '%d товар', '%d товаров', $term->count ), $term->count );
$query = new WP_Query( array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $category_id,
'include_children' => true,
),
),
'nopaging' => true,
'fields' => 'ids',
) );
if( function_exists("is_shop") && $category_id != 0) {
echo '(' .esc_html( $query->post_count ) . ')';
}
}
Paste in your template
<?php do_action('count_product_title');?>

How to set the featured image of a post from the Media Library

If I create a post with this function:
function write_post_with_featured_image( $post_title, $categories ) {
$category_names_array = explode( ",", $categories );
$category_ids = array( );
foreach ( $category_names_array as $category_name ) {
$category_id = get_cat_ID( $category_name );
array_push( $category_ids, $category_id );
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags( $post_title ),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids,
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
echo "post_id: " . $post_id;
}
How can I set it's featured image already existing in the Media Library?
Hopefully everyone will enjoy this function that creates a post and set's it's featured image from the Media Library:
function write_post_with_featured_image($post_title, $categories, $image_in_library_url) {
$category_names_array = explode(",", $categories);
$category_ids = array();
foreach ($category_names_array as $category_name) {
$category_id = get_cat_ID($category_name);
array_push($category_ids, $category_id);
}
// Create post object
$my_post = array(
'post_title' => wp_strip_all_tags($post_title),
'post_status' => 'publish',
'post_author' => 1,
'post_category' => $category_ids
);
// Insert the post into the database
$post_id=wp_insert_post( $my_post );
echo "post_id:" . $post_id;
//Get Image Attachment Id
$attachment_id = attachment_url_to_postid( $image_in_library_url );
echo "attachment_id:" . $attachment_id;
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attachment_id );
echo "featured image added";
}
}
$post_title = 'My Super Post';
$categories = 'Category1,Category2';
$image_in_library_url = "http://localhost/wp-content/uploads/2018/06/my-super-image.jpg";
write_post_with_featured_image($post_title,$categories,$image_in_library_url);

Wordpress native gallery - own output - sorting difficulty

as you can read, I'm having trouble sorting the gallery in the order I want it to. I'm trying to have it sorted just like in the Drag&Drop Interface, where you edit your gallery. That's the same order as in the id attribute in the shortcode. I just can't figure out what value to assign to $orderby. i tried 'ID', 'menu_order' and 'post__in', but no changes.
Do you have any advice.
add_filter('post_gallery', 'fgf_gallery', 10, 2);
function fgf_gallery($output, $attr) {
global $post;
static $instance = 0;
$instance++;
$id = $post->ID;
$order = 'ASC';
$orderby = 'ID';
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
if ( empty($attachments) ) return;
$output = "<ul id='gallery-{$instance}' class='gallery'>";
foreach ( $attachments as $id => $attachment ) {
$output .= "<li class='gallery-item'>";
$output .= "<img src='".$thumb_src."'>";
$output .= "<h1>".$attachment->post_title."</h1>";
if ( trim($attachment->post_excerpt) ) {
$output .= "
<p class='wp-caption-text gallery-caption'>
" . wptexturize($attachment->post_excerpt) . "
<p>";
}
$output .= "</li>";
}
$output .= "</ul>\n";
return $output;
}
Thanks. I appreciated any hint to further documentation as well.
I found what I needed in the wp-includes/media.php file
you get the order from your shortcode with "post__in".
function fgf_gallery_2($output, $attr) {
static $instance = 0;
$instance++;
$order = 'ASC';
$orderby = 'post__in';
$include = $attr['ids'];
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
$attachments = array();
foreach ( $_attachments as $key => $val ) {
$attachments[$val->ID] = $_attachments[$key];
}
if ( empty($attachments) ) return;
$output = "<ul id='gallery-{$instance}' class='gallery'>";
foreach ( $attachments as $id => $attachment ) {
/* do what you want here */
}
$output .= "</ul>\n";
return $output;
}
works for me.

Resources