I'm trying to create a new post (type event) every time one of my posts is updated and custom_field has the value 'ja'.
I don't understand why the if query if($customfield == 'ja'){}
doesn't work.
function create_event($post_id, $post, $post_before){
if (get_post_type($post) == 'product') {
$customfield=get_post_meta($post_id, 'custom_field');
if ($customfield == 'ja') { //this if query doesn't work
$author = $post->post_author;
$event = array(
'post_type' => 'tribe_events',
'post_title' => get_the_author_meta('firmenname', $author),
'meta_input' => array('post_id' => $post_id, '_EventStartDate' => '2019-06-04 00:00', '_EventEndDate' => '2019-06-04 23:59',
'test'=>$customfield)
);
wp_insert_post($event);
}
}
add action('post_updated', 'create_event', 10, 3);
function create_event($post_id, $post, $post_before){
if (get_post_type($post) == 'product') {
$customfield=get_post_meta($post_id, 'custom_field', true);
if ($customfield == 'ja') { //this if query doesn't work
$author = $post->post_author;
$event = array(
'post_type' => 'tribe_events',
'post_title' => get_the_author_meta('firmenname', $author),
'meta_input' => array('post_id' => $post_id, '_EventStartDate' => '2019-06-04 00:00', '_EventEndDate' => '2019-06-04 23:59',
'test'=>$customfield)
);
wp_insert_post($event);
}
}
add action('post_updated', 'create_event', 10, 3);
to get value in variable you need to write this
$customfield=get_post_meta($post_id, 'custom_field', true);
Related
WooCommerce pagination is not fetching products according to posts per page option value. It shows different products when click on pagination link, sometimes show correct number of products on click of pagination link but some time not. Same query is working for all custom pagination.
Here is my code:
public function render()
{
global $wp_query, $wp_rewrite;
$args= [];
$ordering_args =[];
$pagination_args =[];
$taxonomy = 'product_cat';
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => absint(get_option('posts_per_page')),
);
if (isset($_POST['orderby'])) {
if ('price-desc' === $_POST['orderby']) {
$args['orderby'] = 'price';
$args['order'] = 'DESC';
} elseif ('price' === $_POST['orderby']) {
$args['orderby'] = 'price';
$args['order'] = 'ASC';
} elseif ('date' === $_POST['orderby']) {
$args['orderby'] = 'date';
$args['order'] = 'DESC';
} else {
$args['orderby'] = $_POST['orderby'];
$args['order'] ='';
}
$ordering_args = WC()->query->get_catalog_ordering_args($args['orderby'], $args['order']);
$args['orderby'] = $ordering_args['orderby'];
$args['ordering_args'] = $ordering_args;
$args['order'] = $ordering_args['order'];
if ($ordering_args['meta_key']) {
$args['meta_key'] = $ordering_args['meta_key'];
}
}else{
$ordering_args = WC()->query->get_catalog_ordering_args();
$args['orderby'] = $ordering_args['orderby'];
$args['ordering_args'] = $ordering_args;
$args['order'] = $ordering_args['order'];
if ($ordering_args['meta_key']) {
$args['meta_key'] = $ordering_args['meta_key'];
}
}
if (isset($_POST['paged'])) {
$args['paged'] = absint($_POST['paged']);
if (1 < absint($_POST['paged'])) {
$args['paged'] = absint($_POST['paged']);
}
$pagination_args = array(
'total' => wc_get_loop_prop('total_pages'),
'current' =>absint($_POST['paged']),
);
$args['limit'] = isset($args['posts_per_page']) ? intval($args['posts_per_page']) : intval(get_option('posts_per_page'));
if (empty($args['offset'])) {
$args['offset'] = 1 < $args['paged'] ? ($args['paged'] - 1) * $args['limit'] : 0;
}
}
if (!empty($args['meta_query'])) {
if (!empty($_POST['rating'])) {
$args['meta_query']['relation'] ='AND';
$rating = $_POST['rating'];
$args['meta_query'][]= array(
'key' => '_wc_average_rating',
'value' => array( (int)$rating[0], (int)$rating[1] ),
'compare' => 'BETWEEN',
'type' => 'numeric'
);
}
} else {
if (!empty($_POST['rating'])) {
$rating = $_POST['rating'];
$args['meta_query']= array(
array(
'key' => '_wc_average_rating',
'value' => array( (int)$rating[0], (int)$rating[1] ),
'compare' => 'BETWEEN',
'type' => 'numeric'
)
);
}
}
if (!empty($_POST['product-cata'])) {
$category = $_POST['product-cata'];
$args['tax_query']= array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => (int)$category
)
);
}else{
if (!empty($_POST['category'])) {
$category = $_POST['category'];
$args['tax_query']= array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => (int)$category
)
);
}
}
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) {
ob_start();
// do_action('woocommerce_before_shop_loop');
woocommerce_product_loop_start();
while ($wp_query->have_posts()) {
$wp_query->the_post();
/**
* Hook: woocommerce_shop_loop.
*/
do_action('woocommerce_shop_loop');
echo wc_get_template_part('content', 'product');
}
woocommerce_product_loop_end();
//do_action('woocommerce_after_shop_loop');
wp_reset_postdata();
$_RESPONSE['posted_data'] =$_POST;
$_RESPONSE['products'] = ob_get_contents();
ob_end_clean();
if (isset($_POST['paged'])) {
$paged = (int) $_POST['paged'];
$base = $_POST['link'].'page/%#%';
$pagination_args = array(
'base' => $base,
'total' => (int)$wp_query->max_num_pages,
'per_page' => (int)get_option('posts_per_page'),
'current' => (int) max(1, $paged),
'format' => '',
);
$_RESPONSE['pagination'] = $this->custom_woocommerce_pagination($pagination_args);
$_RESPONSE['result_counts'] = $this->custom_result_count($pagination_args);
} else {
$base = $_POST['link'].'page/%#%';
$pagination_args = array(
'base' => $base,
'total' =>(int) $wp_query->max_num_pages,
'per_page' =>(int) get_option('posts_per_page'),
'current' => (int) max(1, 1),
'format' => '',
);
$_RESPONSE['pagination'] = $this->custom_woocommerce_pagination($pagination_args);
$_RESPONSE['result_counts'] = $this->custom_result_count($pagination_args);
}
$_RESPONSE['args'] = $args;
$_RESPONSE['pagination_args'] = $pagination_args;
} else {
ob_start();
do_action('woocommerce_no_products_found');
$_RESPONSE['products'] = ob_get_contents();
$_RESPONSE['args'] = $args;
ob_end_clean();
}
echo json_encode($_RESPONSE);
die();
}
Any help will appreciate. I am using this in ajax post method.
/*Display only in stock*/
$args['meta_query'][]= [
'key' => '_stock_status',
'value' => 'instock'
];
/*Display only visible product*/
$args['tax_query'][]= [
'taxonomy' => 'product_visibility',
'terms' => array( 'exclude-from-catalog' ),
'field' => 'name',
'operator' => 'NOT IN',
];
I want to add a new attribute to an existing woocommerce product. I use this code
$pf = new WC_Product_Factory();
$product = $pf->get_product(76);
//Create the attribute object
$attribute = new WC_Product_Attribute();
$attribute->set_id( 0 );
//pa_color slug
$attribute->set_name( 'color' );
//Set terms slugs
$attribute->set_options( array(
'blue',
) );
$attribute->set_position( 0 );
//If enabled
$attribute->set_visible( 1 );
$product->set_attributes(array($attribute));
$id = $product->save();
this code working fine but I want to add attributes with terms, this code create custom product attribute.
I want to create attribute like this image
How can I create key-value attributes?
Try this code
function get_attribute_id_from_name($name)
{
global $wpdb;
$attribute_id = $wpdb->get_var("SELECT attribute_id
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return $attribute_id;
}
function save_product_attribute_from_name($name, $label = '', $set = true)
{
if (!function_exists('get_attribute_id_from_name')){
return;
}
global $wpdb;
$label = $label == '' ? ucfirst($name) : $label;
$attribute_id = get_attribute_id_from_name($name);
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
if (empty($attribute_id)) {
$attribute_id = NULL;
}
else {
$set = false;
}
//register existing taxonomy
if (isset($attribute_id) && !taxonomy_exists($taxonomy)) {
register_attribute($name);
}
$args = array(
'attribute_id' => $attribute_id,
'attribute_name' => $name,
'attribute_label' => $label,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0,
);
if (empty($attribute_id)) {
$wpdb->insert("{$wpdb->prefix}woocommerce_attribute_taxonomies", $args);
set_transient('wc_attribute_taxonomies', false);
}
if ($set) {
$attributes = wc_get_attribute_taxonomies();
$args['attribute_id'] = get_attribute_id_from_name($name);
$attributes[] = (object)$args;
//print_r($attributes);
set_transient('wc_attribute_taxonomies', $attributes);
} else {
return;
}
}
function register_attribute($name)
{
$taxonomy = wc_attribute_taxonomy_name($name); // The taxonomy slug
$attr_label = ucfirst($name); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($name)); // attribute slug
register_taxonomy(
$taxonomy,
'product',
array(
'label' => __($attr_label),
'rewrite' => array('slug' => $attr_name),
'hierarchical' => true,
)
);
}
function add_product_attribute($product_id, $data)
{
$_pf = new WC_Product_Factory();
$product = $_pf->get_product($product_id);
$product_attributes = array();
foreach ($data['_attributes'] as $key => $terms) {
$taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
$attr_label = ucfirst($key); // attribute label name
$attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug
// NEW Attributes: Register and save them
if (!taxonomy_exists($taxonomy))
save_product_attribute_from_name($attr_name, $attr_label);
$product_attributes[$taxonomy] = array(
'name' => $taxonomy,
'value' => '',
'position' => '',
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 1
);
foreach ($terms as $value) {
$term_name = ucfirst($value);
$term_slug = sanitize_title($value);
// Check if the Term name exist and if not we create it.
if (!term_exists($value, $taxonomy))
wp_insert_term($term_name, $taxonomy, array('slug' => $term_slug)); // Create the term
// Set attribute values
wp_set_object_terms($product_id, $term_name, $taxonomy, true);
}
$product->set_attributes(array($attribute));
}
update_post_meta($product_id, '_product_attributes', $product_attributes);
}
Then call function
add_product_attribute(76, [
'attributes' => [
'Attribute 1' => ['Value 1', 'Value 2'],
'Attribute 2' => ['Value 4', 'Value 5'],
],
]
);
I`ve made this action:
add_action( 'init', 'advanced_search_query' );
function advanced_search_query( $query ) {
if ( isset($_GET['make']) && isset($_GET['model']) && isset($_GET['fuel']) ) {
$all_products = [];
$inner_cats = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $_GET['model']]);
foreach ($inner_cats as $cat) {
if ($_GET['fuel'] == 0)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Diesel']);
elseif ($_GET['fuel'] == 1)
$fuel_cat = get_terms(['taxonomy' => 'product_cat','hide_empty' => false, 'parent' => $cat->term_id, 'name' => 'Benzin']);
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => $fuel_cat[0]->term_id,
'operator' => 'IN',
)
)
);
$products = get_posts( $args );
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
}
}
}
}
}
Now what I am strugling with is sending the $all_products to my search page and loop them. Tried to redirect to the search page like wp_safe_recirect('domain.com?s=""') with empty s parameter and use the all_results there. Also tried to set the variable as global but again couldnt reach it.
Did you try the following?
if ($products) {
foreach ($products as $prd) {
$all_products[] = $prd;
?>
<script>window.location.href="domain.com?s=''"</script>
<?php
}
}
I am researching more and use the code..
I have done this code.
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic
{
public static function createTemplate( ) {
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id )
wp_die('Error creating template page');
else
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
but create multiple page after refresh.
Is there any good way to create the page like as woocommerce does??
So code be like something
if (!defined('ABSPATH')) {
die;
}
if(!class_exists('ArtistPublic')):
class ArtistPublic {
public static function createTemplate( ) {
if( get_option('artist_page_id') ) :
global $user_ID;
$new_post = array(
'post_title' => 'Artist',
'post_content' => 'hello Artist',
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_ID,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
if( !$post_id ) :
wp_die('Error creating template page');
else :
update_option('artist_page_id', $post_id);
update_post_meta( $post_id, '_wp_page_template', 'artist.php' );
endif;
endif;
// Filter page template
// add_filter('page_template', 'catch_plugin_template');
}
// Page template filter callback
public static function catch_plugin_template($template) {
if( is_page_template('artist.php') )
$template = WP_PLUGIN_DIR . '/ItgArtist/public/templates/artist.php';
return $template;
}
}
endif;
Currently I have a category called 'vou' and would like to just get shop_order under this category. I have tried many combinations and it's not working out. Thank you for reading:
$args = array(
'post_type' =>'shop_order',
'post_status' => array_keys( wc_get_order_statuses() ),
'posts_per_page' => -1,
'orderby'=> 'date',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'vou'//,
//'terms' => get_terms( 'product_cat', array( 'fields' => 293 ) ),
)
)
);
How to get shop_order by product category 'vou'?
Find all your orders and gether orders that have required category. Make new args with post__in attribute.
$m_args_all = array(
'orderby' => 'date',
'posts_per_page' => 12,
);
$ordr_cat = 654 // id of required cat
$empty_cat = false;
$orders_all_raw = wc_get_orders( $m_args_all ); //find all orders by your args
if (!empty($orders_all_raw)) {
$orders_in_cat = [];
foreach ($orders_all_raw as $order_raw) {
$items = $order_raw->get_items(); //get products of order
if (!empty($items)) {
foreach ($items as $item_id => $item) { //loop for products
$term_ids = wp_get_post_terms($item->get_product_id(), 'product_cat', array('fields' => 'ids')); // get all id of cats in product
if (in_array($ordr_cat, $term_ids)) { // if required cat in array of gethered cats add order id to array
if (!in_array($order_raw->ID, $orders_in_cat)) {
$orders_in_cat[] = $order_raw->ID; //add order with required prod cat to array
}
}
}
}
}
if (empty($orders_in_cat)){
$empty_cat = true;
}
else {
$m_args_all += array('post__in' => $orders_in_cat);
}
}
if($empty_cat){
$orders = [];
}
else{
$orders = wc_get_orders( $m_args_all );
}