Generate WordPress Post Tittle from ACF Fields - wordpress

I am trying to generate a custom post title from two ACF fields. I have first_name and last_name but it will only generate the last name and does it twice:
/contacts/deere-deere/
Here's my function:
function update_contacts_title( $value, $post_id, $field ) {
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('last_name', $post_id). ' ' . $value;
$title = $first_name .' - '. $last_name;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=first_name', 'update_contacts_title', 10, 3);
add_filter('acf/update_value/name=last_name', 'update_contacts_title', 10, 3);
If I modify this line down like so, then it will generate the first_name but only once:
/contacts/john/
//Create new title based on ACF Fields
function update_contacts_title( $value, $post_id, $field ) {
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('last_name', $post_id). ' ' . $value;
//$title = $first_name .' - '. $last_name;
$title = $first_name;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=first_name', 'update_contacts_title', 10, 3);
//add_filter('acf/update_value/name=last_name', 'update_contacts_title', 10, 3);
This is really confusing me as to why it won't recognize both the first name and last name.
Any suggestions would be extremely helpful, thank you all.

You have "first_name" for both the names I believe.
$first_name = get_field('first_name', $post_id). ' ' . $value;
$last_name = get_field('first_name', $post_id). ' ' . $value;

Here's the answer I figured out after I remembered that I have the first_name and last_name in a group, which requires a repeater field in the function:
function update_contacts_title($post_id) {
if( have_rows('contact_info') ):
while( have_rows('contact_info') ): the_row();
$first_name = get_sub_field('first_name', $post_id);
$last_name = get_sub_field('last_name', $post_id);
$title = $first_name . '-' . $last_name;
$slug = sanitize_title( $title );
endwhile;
endif;
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'contacts',
'post_name' => $slug
);
wp_update_post( $postdata );
}
add_filter('acf/save_post', 'update_contacts_title', 10, 3);

Related

wp_insert_post generating duplicate id

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?!

Uploade user image in wordpress using json api

I am developing the mobile app using WordPress database. I created a user and changing user details using JSON API. But I don't know how to upload user image from mobile to WordPress database using API. Can anyone help me out?
Try this code. I'm using this code for upload user profile image in API
you have to convert image to base64_encode in mobile and send to API
<?php
$password = esc_attr( $password );
$random_password = wp_generate_password( 12, false );
$email = sanitize_email( $useremail );
$first_name = sanitize_text_field( $firstname );
$phoneno = sanitize_text_field( $phoneno );
$type = sanitize_text_field( $type );
$imgdata = base64_decode($data["avatar"]);
$userdata = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
'user_nicename' => $first_name,
'first_name' => $first_name,
'last_name' => '',
);
$new_user = wp_insert_user ( $userdata );
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$type_file = explode('/', $mime_type);
$avatar = time() . '.' . $type_file[1];
$uploaddir = wp_upload_dir();
$myDirPath = $uploaddir["path"];
$myDirUrl = $uploaddir["url"];
file_put_contents($uploaddir["path"].'/'.$avatar,$imgdata);
$filename = $myDirUrl.'/'.basename( $avatar );
$wp_filetype = wp_check_filetype(basename($filename), null );
$uploadfile = $uploaddir["path"] .'/'. basename( $filename );
$attachment = array(
"post_mime_type" => $wp_filetype["type"],
"post_title" => preg_replace("/\.[^.]+$/", "" , basename( $filename )),
"post_content" => "",
"post_status" => "inherit",
'guid' => $uploadfile,
);
require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . 'wp-admin' . '/includes/file.php');
require_once(ABSPATH . 'wp-admin' . '/includes/image.php');
$attachment_id = wp_insert_attachment( $attachment, $uploadfile );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );
wp_update_attachment_metadata( $attachment_id, $attach_data );
update_post_meta($attachment_id,'_wp_attachment_wp_user_avatar',$new_user);
update_user_meta($new_user, 'wp_user_avatar', $attachment_id);

WordPress taxonomy images plugin displaying all terms

I am using taxonomy-images/ WordPress plugin (https://en-gb.wordpress.org/plugins/taxonomy-images/)
Target: I have got a poster taxonomy and I would like to display term name and term image. I would like to be able to display, retrieve ALL terms in my taxonomy, no matter term name is empty.
Issue: But if both data are not entered I can not display the term. I am not managing to correctly make use of 'hide_empty'.
Any help appreciated.
Thanks
<?php
/*
Template Name: gof Poster Home Page */
// https://en-gb.wordpress.org/plugins/taxonomy-images/
?>
<?php
$taxonomy = 'month-category';
$orderby = 'name';
$order = 'ASC';
$show_count = false;
$pad_counts = false;
$hierarchical = true;
$hide_empty = false;
$title = '';
$images = 'image_id';
$args = array(
'taxonomy' = $taxonomy,
'orderby' = $orderby,
'order' = $order,
'show_count' = $show_count,
'pad_counts' = $pad_counts,
'hierarchical' = $hierarchical,
'hide_empty' = $hide_empty,
'title_li' = $title
);
//$terms = get_terms( 'month-category', $args );
// $terms = apply_filters( 'taxonomy-images-get-terms', 'month-category', $args);
$terms = apply_filters( 'taxonomy-images-get-terms', '', $args);
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
$count = count( $terms );
$i = 0;
$term_list = '<div id="poster-cat-wrapper">';
foreach ( $terms as $term ) {
$term_list .=
'<div class="poster-cat">' .
'<a href="/posters/?gof=' . $term->name . '">' .
wp_get_attachment_image( $term->$images, 'detail' ) .
'<p>' . $term->name . '</p>' .
'</a>' .
'</div>';
$i++;
// '' . $term->name . ''
if ( $count != $i ) {
$term_list .= ' ';
}
else {
$term_list .= '</div>';
}
}
}
?>
I cannot figure out how to do this either, but I found a nasty hack. Look for this part in 'public-filters.php' in '/plugins/taxonomy-images/':
$args = wp_parse_args( $args, array(
'cache_images' => true,
'having_images' => true,
'taxonomy' => 'category',
'term_args' => array('hide_empty' => false),
) );
Change it to this:
$args = wp_parse_args( $args, array(
'cache_images' => true,
'having_images' => true,
'taxonomy' => 'category',
'term_args' => array('hide_empty' => false),
) );
Once again: Know that this is NOT the right solution! You should write a filter that does this for you. Every plugin update will break this functionality.

Woocommerce, sort dropdown on shortcode based product lists

In our shop, we have a number of standard WP pages. On these pages we show ~40 products using the standard Woocommerce shortcodes.
For example:
[product_category category="boots" per_page="20" columns="4" orderby="price" order="desc"]
The products appears, but there are two things missing:
No sorting dropdown appears above the product lists, so the products cannot be sorted by our visitors.
We don't see any pagination buttons, so it's impossible to see more than the first 20 products on each page.
Any ideas how we can fix those two things?
Regarding your first issue, I have not found any good solutions beside hacking the shortcode within WC. Not entirely advisable as it will be overwritten each upgrade/patch of WC. If it's absolutely necessary, you could maintain the code by rewriting the hack each time you upgrade.
Alright, first download a copy of includes\class-wc-shortcodes.php in your woocommerce folder. Make a backup of the original before editing it, I usually rename the file with a -o or change the file type to .bak.
Assuming you'd want the original sort by dropdown that comes with WC on the Shop Page.
Step 1
Remove orderby and order arguments on the shortcode:
[product_category category="boots" per_page="20" columns="4"]
Step 2
Edit the Product Category shortcode on class-wc-shortcodes.php as such:
/**
* List products in a category shortcode
*
* #access public
* #param array $atts
* #return string
*/
public static function product_category( $atts ) {
global $woocommerce_loop, $wpdb;
if ( empty( $atts ) ) return '';
extract( shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'asc',
'category' => '',
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
), $atts ) );
if ( ! $category ) return '';
// Default ordering args
// $ordering_args = WC()->query->get_catalog_ordering_args( $orderby, $order ); // COMMENT THIS OUT
$orderby = 'title';
$order = 'asc';
if ( isset( $_GET['orderby'] ) ) {
$getorderby = $_GET['orderby'];
}
if ($getorderby == 'popularity') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = 'total_sales';
} elseif ($getorderby == 'rating') {
$fields .= ", AVG( $wpdb->commentmeta.meta_value ) as average_rating ";
$where .= " AND ( $wpdb->commentmeta.meta_key = 'rating' OR $wpdb->commentmeta.meta_key IS null ) ";
$join .= "
LEFT OUTER JOIN $wpdb->comments ON($wpdb->posts.ID = $wpdb->comments.comment_post_ID)
LEFT JOIN $wpdb->commentmeta ON($wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id)
";
$orderby = "average_rating DESC, $wpdb->posts.post_date DESC";
$groupby = "$wpdb->posts.ID";
} elseif ($getorderby == 'date') {
$orderby = 'date';
$order = 'desc';
} elseif ($getorderby == 'price') {
$orderby = 'meta_value_num';
$order = 'asc';
$meta_key = '_price';
} elseif ($getorderby == 'price-desc') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = '_price';
}
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => $orderby, // $ordering_args['orderby'],
'order' => $order, // $ordering_args['order'],
'meta_key' => $meta_key,
'fields' => $fields,
'where' => $where,
'join' => $join,
'groupby' => $groupby,
'posts_per_page' => $per_page,
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
'operator' => $operator
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $args, $atts ) );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<div style="width:100%;">
<div style="float:right">
<form class="woocommerce-ordering" method="get">
<select name="orderby" class="orderby">
<?php
$catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
'menu_order' => __( 'Default sorting', 'woocommerce' ),
'popularity' => __( 'Sort by popularity', 'woocommerce' ),
'rating' => __( 'Sort by average rating', 'woocommerce' ),
'date' => __( 'Sort by newness', 'woocommerce' ),
'price' => __( 'Sort by price: low to high', 'woocommerce' ),
'price-desc' => __( 'Sort by price: high to low', 'woocommerce' )
) );
if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' )
unset( $catalog_orderby['rating'] );
foreach ( $catalog_orderby as $id => $name )
echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
?>
</select>
<?php
// Keep query string vars intact
foreach ( $_GET as $key => $val ) {
if ( 'orderby' === $key || 'submit' === $key )
continue;
if ( is_array( $val ) ) {
foreach( $val as $innerVal ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
}
} else {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
}
}
?>
</form>
</div>
</div>
<div style="clear:both;"></div>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
Upload the file back into the includes folder and you're done! Your shortcode product pages will now have a working sort by dropdown same as the one that appears on the WC Shop Page.
Edit the sort options to your liking! Hope it helps!
Well for your second problem: Your shortcode is limiting to see only 20 products. Change the it to per_page="40" and you should see 40 products or simply remove the line and the number of products is not limited.
For your first problem I don't have an answer. I'm looking it for my self as well :).
If you add the paginate="true" attribute to your [products] shortcode, then the shortcode, then the Sort by dropdown menu will appear on the page.
Change this
[product_category category="boots" per_page="20" columns="4"]
to this
[product_category category="boots" paginate="true" limit="20" columns="4"]

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