i want to get woocommerce thumbnail src url in array - wordpress

I want get thumbnail image url in the following image attribute
$product = wc_get_product( $post->ID ); //do this instead
$end_point = 'https://api.webpushr.com/v1/notification/send/sid';
//do a wp_remote_post instead of cURL
$body = array(
'title' => $product->get_name(),
'message' => 'check out now',
'target_url' => $product->get_permalink(),
'image' => $product->get_image($attr = array( 'src'=>get_the_post_thumbnail_url())), // Here I want to get Image thumbnail url. But it is not working
'sid' => '113858026',
);

You can write it like this:
'image' => wp_get_attachment_image_url( $product->get_image_id(), 'thumbnail' )
where you get the image id using $product->get_image_id() then you use wp_get_attachment_image_url to get the url.

Related

Insert wordpress post using wp_insert_post and attach the featured image

I tried to insert a post using the wp_insert_post function in the functions.php file, the post successfully inserted, but not for the attachment for featured image.
Anyone can help on this, what's wrong with my code below:
$post_if = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_title like '$title'");
if($post_if < 1){
//coded
$new_post = array(
'post_title' => $title,
'post_content' => $contents,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
$image = "https://fake.org/image.jpg";
$media = media_sideload_image($image, $post_id); //$post_id from wp_insert_post
// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'any',
'post_parent' => $post_id
);
// reference new image to set as featured
$attachments = get_posts($args);
if(isset($attachments) && is_array($attachments)){
foreach($attachments as $attachment){
// grab source of full size images (so no 300x150 nonsense in path)
$image = wp_get_attachment_image_src($attachment->ID, 'full');
// determine if in the $media image we created, the string of the URL exists
if(strpos($media, $image[0]) !== false){
// if so, we found our image. set it as thumbnail
set_post_thumbnail($post_id, $attachment->ID);
// only want one image
break;
}
}
}
}
I tried so many tutorials, I found over the web, nothing to work.
Please any one has experienced with this can share a solution.
Big Thanks
You would need to set the "featured image" first and then try to query it. You tried to do the opposite. Also set the parent id in the wp_insert_attachment function not in the arguments.
So try this code:
$new_post = array(
'post_title' => $title,
'post_content' => $contents,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post'
);
$post_id = wp_insert_post($new_post);
$image = "https://fake.org/image.jpg";
$attachment_file_type = wp_check_filetype(basename($image), null);
$wp_upload_dir = wp_upload_dir();
$attachment_args = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($image),
'post_title' => preg_replace('/\.[^.]+$/', '', basename($image)),
'post_mime_type' => $attachment_file_type['type']
);
$attachment_id = wp_insert_attachment($attachment_args, $image, $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_meta_data = wp_generate_attachment_metadata($attachment_id, $image);
wp_update_attachment_metadata($attachment_id, $attachment_meta_data);
set_post_thumbnail($post_id, $attachment_id);
Here's the documentation page for
wp_insert_attachment
Reference:
https://developer.wordpress.org/reference/functions/wp_insert_attachment/#user-contributed-notes

Change Wordpress User Profile Photo By Id

Attempting to change several of my users profile pics (via code).
I am using Ultimate Members & WP User Avatar but have not come to a good resolution as yet.
I really need a function that can be passed the user ID and a URL (of profile pic.
something on the line of
function set_avatar_url($avatar_url, $user_id) {
global $wpdb;
$file = upload_product_image($avatar_url);
$wp_filetype = wp_check_filetype($file['file']);
$attachment = array(
'guid' => $file['url'],
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['file'])),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file['file']);
$attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
wp_update_attachment_metadata($attach_id, $attach_data);
update_user_meta($user_id, $wpdb->get_blog_prefix() . 'user_avatar', $attach_id);
}
set_avatar_url('https:/mysite.com/Logo-test2.png', 5);
Am I asking too much?

Fieldmanager Wordpress plugin

I need to find a way to display values saved in custom meta boxes. Meta Boxes are created with WP Fieldmanager plugin.
Here is the code used to display fields in the post admin:
add_action( 'init', function() {
$fm = new Fieldmanager_Group( array(
'name' => 'sidebar',
'limit' => 0,
'label' => 'Sidebar Section',
'label_macro' => array( 'Section: %s', 'name' ),
'add_more_label' => 'Add another Sidebar Section',
'children' => array(
'name' => new Fieldmanager_Textfield( 'Section Heading' ),
'item' => new Fieldmanager_Textfield( 'Item', array(
'limit' => 0,
'one_label_per_item' => true,
'add_more_label' => 'Add another Item',
) ),
),
)
);
$fm->add_meta_box( 'Sidebar', array( 'post' ) );
} );
You can see this is actually a repeating group which has a repeating field inside. I need to display meta values from those groups.
Thanks.
You have to use foreach() to get out the content:
$repeating_fields = get_post_meta( get_the_ID(), 'sidebar', true); //name of your custom field;
foreach ($repeating_fields as $repeating_field) {
print_r($repeating_field[name]); //use here the name given to your children in array to select the correct one;
}
From here you if know how to arrange a foreach loop you should be good.
If you want to get the metabox content as an array you can do like this:
$repeating_fields = get_post_meta( get_the_ID(), 'sidebar', true);
$name = array(); //define the variable as an array from the start;
foreach ($repeating_fields as $repeating_field) { //start the loop
$name[] = $repeating_field[name]; //get the array content from the meta box
}
echo $name; //echo the array or parts of it

How can I get the Posts created with ACF in Wordpress?

I added this to my function.php for saving the post:
function my_pre_save_post( $post_id )
{
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_status' => 'draft' ,
'post_title' => 'A title, maybe a $_POST variable' ,
'post_type' => 'post' ,
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
And on the page.php I've got this code:
$postid = get_the_ID();
if($postid ==50){ //50 is a Page I created for the Form
$options = array(
'post_id' => 'new',//$post->ID, // post id to get field groups from and save data to
'field_groups' => array(46), // this will find the field groups for this post (post ID's of the acf post objects)
'form' => true, // set this to false to prevent the <form> tag from being created
'form_attributes' => array( // attributes will be added to the form element
'id' => 'post',
'class' => '',
'action' => '',
'method' => 'post',
),
'return' => add_query_arg( 'updated', 'true', get_permalink() ), // return url
'html_before_fields' => '', // html inside form before fields
'html_after_fields' => '', // html inside form after fields
'submit_value' => 'Update', // value for submit field
'updated_message' => 'Post updated.', // default updated message. Can be false to show no message
);
acf_form( $options );
}
Now, I think the saving was successfull, how do I get the whole Posts that have been created with this Form?
I tried this (on page with ID 51), but I get nothing:
$posts = get_posts(array(
'post_type' => 'event',
'posts_per_page' => -1,
'meta_key' => 'location',
'meta_value' => 'melbourne'
));
if($posts)
{
foreach($posts as $post)
{
the_field('titel');
}
}
The ACF Plugin for Wordpress is very well documented, but I couldnt solve my problem.
http://www.advancedcustomfields.com/resources
according to the ACF form field documentation https://www.advancedcustomfields.com/resources/acf_form/
the "return" field has 2 dynamic placeholders
"(String) The URL to be redirected to after the form is submitted.
Defaults to the current URL with a GET parameter ‘?updated=true’. A
special placeholder ‘%post_url%’ will be converted to post’s
permalink. A special placeholder ‘%post_id%’ will be converted to
post’s ID."
if you add 'return' => '?newpost=%post_id%', for example, you get back your original page with the new post id as URL parameter that you can handle with PHP in your page template
The documentation says you've to set the post_id value inside your $options array to new_post instead of new if you want to create a new post. Also you've to use the new_post array key with an array with data for the new post as value for the key.
Check out the acf_form documentation. This is what I basically mean:
$options = array(
'post_id' = 'new_post',
'new_post' = array(
//new post data
)
);

Attach image to post in Wordpress XMLRPC

I am using XMLRPC to do posts to Wordpress. I am having issues posting thumbnails, after debugging wordpress code I see that my issue is caused by the fact that the image is not attached to the post.
I must do this without patching wordpress or using PHP, only iwth XMLRPC.
I can upload an image and get the ID of the image.
Other point that confuses me is how do you attach an image to a post that you did not posted yet because you wait for the image to upload? I am supposed to upload image then post ,then using the image id and the post id do an update on the image metadata?
Edit: the code in wordpress that is problematic is this check
if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
and my assumption it is that it fails because the image is Unattached, if i fix that code all is fine but I can't patch the WP of my application users(so this is not a solution)
Yes it is possible to do it, if Wordpress version is 3.5 or greater,when using the code for uploading file/image you can set the post_id.
The flow I used for new posts with featured images is like this:
use the newPost function and post the content without the featured
image and also set publish to false, record the post_id returned by
this
upload the image and set the post_id to the id of the post just
posted, record the image_id
when done edit the post and set the wp_post_thumbnail equal to the
image_id you just uploaded and also set publish to true(if needed)
Important:
The mime type is important, it must be "image/jpg" or "image/png" please see documentation, if mime type is worng like "jpg" attaching will fail.
Tip:
For debugging, if you get a generic error from wordpress and you can't figure out why you can check the wordpress code and even edit it, adding debugging/tracing calls and hopefully you can figure out the cause.
This is an example of a post with category, image and tags. It requires class-IXR.php
https://github.com/WordPress/WordPress/blob/master/wp-includes/class-IXR.php
and mime_content_type function
https://github.com/caiofior/storebaby/blob/master/magmi/plugins/extra/general/socialnotify/wp/mimetype.php
$client = new IXR_Client($url);
$content = array(
'post_status' => 'draft',
'post_type' => 'post',
'post_title' => 'Title',
'post_content' => 'Message',
// categories ids
'terms' => array('category' => array(3))
);
$params = array(0, $username, $password, $content);
$client->query('wp.newPost', $params);
$post_id = $client->getResponse();
$content = array(
'name' => basename('/var/www/sb/img.jpeg'),
'type' => mime_content_type('/var/www/sb/img.jpeg'),
'bits' => new IXR_Base64(file_get_contents('/var/www/sb/img.jpeg')),
true
);
$client->query('metaWeblog.newMediaObject', 1, $username, $password, $content);
$media = $client->getResponse();
$content = array(
'post_status' => 'publish',
// Tags
'mt_keywords' => 'tag1, tag2, tag3',
'wp_post_thumbnail' => $media['id']
);
$client->query('metaWeblog.editPost', $post_id, $username, $password, $content, true);
My version if you want to use only wp.newPost and wp.editPost
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php' );
$usr = 'username_on_the_server_side';
$pwd = 'password_on_the_server_side';
$xmlrpc = 'server side xmlrpc.php url';
$client = new IXR_Client($xmlrpc);
//////////// IMAGE UPLOAD AND ATTACHMENT POST CREATION ///////////
$img_attach = 'link to the image';
$img_attach_content = array(
'name' => basename($img_attach),
'type' => mime_content_type($img_attach),
'bits' => new IXR_Base64(file_get_contents($img_attach)),
);
$status = $client->query( 'wp.uploadFile','1', $usr, $pwd, $img_attach_content );
$image_returnInfo = $client ->getResponse();
//////////// POST CREATION ///////////
$custom_fields = array(
array( 'key' => 'blabla1', 'value' => 'blabla1_value' ),
array( 'key' => 'blabla12', 'value' => 'blabla1_value2')
);
$post_content = array(
'post_type' => 'post',
'post_status' => 'draft', //for now
'post_title' => 'XMLRPC Test',
'post_author' => 3,
'post_name' => 'XMLRPC Test',
'post_content' => 'XMLRPC Test Content',
'custom_fields' => $custom_fields
);
$res = $client -> query('wp.newPost',1, $usr, $pwd, $post_content);
$postID = $client->getResponse();
if(!$res)
echo 'Something went wrong....';
else {
echo 'The Project Created Successfully('.$res.')<br>Post ID is '.$postID.'<br>';
}
//////////// Image Post Attachment Edit ///////////
$img_attach_content2 = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_title' => $postID,
'post_name' => $postID,
'post_parent' => $postID,
'guid' => $image_returnInfo['url'],
'post_content' => '',
'post_mime_type' => 'image/jpg'
);
$res2 = $client -> query('wp.editPost', 0, $usr, $pwd, $image_returnInfo['id'], $img_attach_content2);
$postIDimg = $client->getResponse();
//////////// POST EDIT ///////////
$post_content2 = array(
'post_status' => 'publish', //publish
'wp_post_thumbnail' => $image_returnInfo['id'],
'custom_fields' => array( 'key' => '_thumbnail_id', 'value' => $image_returnInfo['id'] )
);
$media2= $client->query('wp.editPost',0, $usr, $pwd, $postID, $post_content2);
This is my version, using wp.newPost and wp.editPost, added on WordPress 3.4, that allow the use of custom post types.
require_once("IXR_Library.php.inc");
$title = 'My title';
$body = 'My body';
$category="category1, category2"; // Comma seperated pre existing categories. Ensure that these categories exists in your blog.
$keywords="keyword1, keyword2, keyword3";
$customfields=array('key'=>'Author-bio', 'value'=>'Autor Bio Here'); // Insert your custom values like this in Key, Value format
$title = htmlentities($title,ENT_NOQUOTES,#$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,#$encoding);
$content = array(
'post_title'=>$title,
'post_content'=>$body,
'post_type'=>'some_custom_post_type',
'post_status' => 'draft', // http://codex.wordpress.org/Post_Status
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'mt_keywords'=>$keywords,
'categories'=>array($category),
'custom_fields' => array($customfields)
);
// Create the client object
$client = new IXR_Client('http://example.com/xmlrpc.php');
$username = "wp_username";
$password = "wp_username_password";
$params = array(0,$username,$password,$content,true); // Last parameter is 'true' which means post immediately, to save as draft set it as 'false'
if (!$client->query('wp.newPost', $params)) {
die('<br/><strong>Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
else
{
$post_id = $client->getResponse();
echo 'Inserted with id'.$post_id;
$picture = '/full/path/to/pic.jpg';
$content = array(
'name' => basename($picture),
'type' => mime_content_type($picture),
'bits' => new IXR_Base64(file_get_contents($picture)),
true
);
if (!$client->query('metaWeblog.newMediaObject', 1, $username, $password, $content)) {
die('<br/><strong>Something went wrong - newMediaObject'.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
else
{
$media = $client->getResponse();
$content = array(
'post_status' => 'publish',
'post_thumbnail' => $media['id']
);
if (!$client->query('wp.editPost', 0, $username, $password, $post_id, $content)) {
die('<br/><strong>Something went wrong editPost - '.$client->getErrorCode().' : '.$client->getErrorMessage().'<br >');
}
}
}

Resources