Insert some posts in a loop - wordpress plugin - wordpress

I wrote a plugin, which reads csv files and create new products. The plugin works when I create only one product but when I add while in Insert() the plugin doesn't work. I want to create all products first off. Maybe it's something related to the add_action... Please help.
define( 'PLUGIN_DIR', dirname(__FILE__).'/' );
function CreateProduct($line) {
$data = explode('";"', $line);
define(POST_NAME, $data[2]);
define(cena_netto_pw, $data[5]);
$post = get_page_by_title( POST_NAME, 'OBJECT', 'product' );
$product_ID = $post->ID;
$post_data = get_post($product_ID);
function hbt_create_post() {
$my_post = array(
'post_title' => POST_NAME,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' =>'product'
);
$product_ID = wp_insert_post( $my_post );
}
if(!isset($post))
hbt_create_post();
return $error_obj;
}
function Import() {
$file = PLUGIN_DIR.'test.csv';
$open = fopen($file, 'r');
while (!feof($open)) {
$line = fgets($open);
CreateProduct($line);
}
fclose($open);
}
add_action('admin_init', 'Import' );
?>
While loop code
while (!feof($open)) { $line = fgets($open); CreateProduct($line); }
This code doesn't work. It works when there is only
$line = fgets($open); CreateProduct($line);

try
fgetcsv($open)
instead
fgets($open)

Related

I want the most recent comment and the thumbnail of Blog post in WordPress

I am trying to make a shortcode that should pull up the most recent comment (only one), Comment author name and thumbnail of the blog post on which this comment is published no matter if the blog post is the most recent or the older one. The comment should be the most recent one.
I made the code but it is not pulling the most recent comment.
function ct_comment_block(){
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'tax_query' => array(
'taxonomy' => 'calendar_category',
'field' => 'slug'
),
'order' => 'ASC',
'orderby' => 'menu_order'
)
);
$str = '';
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);`$thumb_url = $thumb_url_array[0];
while ($query->have_posts()):
$query->the_post();
$str .= '<div class="comment-main">
<div class="comment-image-wrapper">'.get_the_post_thumbnail().'</div>
<div class="comment-wrapper">
<h3>'.comment_sender().'</h3>
<h5>Traveler Hobbyist</h5>
<p>'.real_body().'</p>
</div>';
$str .= '</div>';
endwhile;
return $str;
}
add_shortcode('show_comment' , 'ct_comment_block');
I have written most of the my anser in the code comments.
But I would use a $wpdb query to fetch the newest comment, get the id of the assosiated post and work from there.
Hopefully this makes sense to you.
<?php
add_shortcode('show_comment' , 'ct_comment_block');
function ct_comment_block(){
if(!is_admin()){
global $wpdb;
$query = "SELECT * from $wpdb->comments WHERE comment_approved= '1' ORDER BY comment_date DESC LIMIT 0 ,1"; // This shows the newest comment
$comments = $wpdb->get_results($query);
$strToReturn = '';
if ($comments) {
$strToReturn .= '<div class="someSortOfWrappingClass">';
foreach ($comments as $comment) {
//Use $comment->comment_post_ID for the post_id like so
$link = get_permalink($comment->comment_post_ID);
//but you can check what else is inside $comment - like $comment->comment_author_email etc.
//Simply gather your html here
} //End of foreach
$strToReturn .= '</div>';
} //End of IF
return $strToReturn;
} else {
return;
}
}
Try it may help you for get most recent comments
$recentcomments = get_comments( array(
'number' => 10, // fetch number of comments.
'status' => 'approve', // status approved comments.
'post_status' => 'publish' // post status published comments.
) );
if ( $recentcomments ) {
foreach ( (array) $recentcomments as $comment ) {
echo '' . get_the_title( $comment->comment_post_ID ) . '';
}
}

Adding a string to wordpress title not adding to backend

I have been inserting title into the wordpress post title from front end it was not storing the string as it is.
$title = $_POST['title'];
$new_help = array(
'post_title' => $title,
'post_status'=> 'publish'
);
wp_insert_post();
the string i am inserting is <<hello_world>>
It was storing only <<>>
I think you just forgot to incorporate the arguments into the wp_insert_post function.
if( isset($_POST['title']) && !empty($_POST['title']) )
{
$title = $_POST['title'];
$new_help = array(
'post_title' => $title,
'post_status'=> 'publish'
);
wp_insert_post($new_help);
}

Wordpress REST API: How to retrieve posts tagged by multiple tags?

Some people suggested using /posts?tags=tag_id_1,tag_id_2 or /posts?tags[]=tag_id_1&tags[]=tag_id_2
but wordpress seems to be returning posts that are tagged either with tag1 OR tag2. What I actually need is posts tagged with tag1 AND tag2.
Anyone has an idea?
I will share with you what I have done.
I created a new endpoint for my custom needs,
which ends like myapi/v1/posts/tag1/tag2
add_action('rest_api_init', function () {
register_rest_route( 'myapi/v1', 'posts/(?P<tag_1>[-\w]+)/(?P<tag_2>[-\w]+)',array(
'methods' => 'GET',
'callback' => 'get_posts_set'
));
});
Then, created
function get_posts_set($request) {
$args = array(
'category_name' => $request['category_name'],
'tag_slug__and' => array( $request['tag_1'],$request['tag_2'] ),
);
$posts = get_posts($args);
if (empty($posts)) {
return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) );
}
// Following code is my processing of output. Customize it to suit your needs
$post_data = array();
$i = 0;
foreach( $posts as $post) {
$post_id = $post->ID;
$post_title = remove_html_comments($post->post_title);
$post_content = remove_html_comments($post->post_content);
$post_data[ $i ][ 'id' ] = $post_id;
$post_data[ $i ][ 'title' ] = $post_title;
$post_data[ $i ][ 'content' ] = $post_content;
$i++;
}
$response = new WP_REST_Response($post_data);
$response->set_status(200);
return $response;
}
function remove_html_comments($content = '') {
return preg_replace('/<!--(.|\s)*?-->/', '', $content);
}
This will return only the PostID, Post Title and Post Content with HTML formatting for direcr reuse. Hope this solves your question.

Gettin atrribute thumbnail from node from a wordpress rss feed

I've been trying to get this seemingly easy peace of code to work.
I'm loading rss from a wordpress site and it all works fine except for the thumbnails. Since in the XML they are set as an attribute instead of a nodeValue i can't seem to get import them. (i've really tried a lot)
$rss = new DOMDocument();
$rss->load('http://goalprogramme.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
// in XML it looks like <media:thumbnail url="http://goalprogramme.files.wordpress.com/2014/01/dsc_0227.jpg?w=150"/>
//echo $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url');
//push items
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
'thumbnail' => $node->getElementsByTagName('media:thumbnail')->item(0)->getAttribute('url') // this line doesn't work !!!
);
array_push($feed, $item);
}
Any help would be greatly appreciated.
Thanks so much in advance!
Hours later i've created another piece of code that does work. If anyone needs it it, here it is:
$feed_array = array();
$feed = simplexml_load_file('http://goalprogramme.wordpress.com/feed/');
foreach ($feed->channel->item as $item) {
$title = (string) $item->title;
$description = (string) $item->description;
$link = (string) $item->link;
$date = (string) $item->date;
if ($media = $item->children('media', TRUE)) {
if ($media->thumbnail) {
$attributes = $media->thumbnail->attributes();
$thumbnail = (string)$attributes['url'];
}
}
$item = array (
'title' => $title ,
'desc' => $description,
'link' => $link,
'date' => $date,
'thumbnail' => $thumbnail
);
array_push($feed_array, $item);
}

insert product type from front end in wordpress

if(isset($_POST['uploadwine']))
{
global $wpdb,$woocommerce;
global $current_user;
$post_status = 'publish';
if(isset($_POST['postid']))
{
$postid=$_POST['postid'];
}else
{
$postid='';
}
$wine_post = array(
'post_title' => $_POST['wine_name'],
'post_status' => $post_status,
'post_author' => $current_user->ID,
'post_type' => 'Product',
);
if( empty($postid)){
echo $postid=wp_insert_post( $wine_post );
update_post_meta($postid, '_thumbnail_id', $_POST['aaiu_image_id'][0]);
$product_meta['year'] = $_POST['year'];
$product_meta['producer'] = $_POST['producer'];
#$product_meta['grapes_variety'] = $_POST['grapes_variety'];
$product_meta['area'] = $_POST['area'];
#$product_meta['tw_share'] = $_POST['Country'];
$product_meta['color'] = $_POST['Color'];
$product_meta['good_answer_for_the_smell_test'] = $_POST['Smell'];
$product_meta['good_answer_for_the_taste_test'] = $_POST['Taste'];
foreach($product_meta as $key =>$value)
{
update_post_meta($postid, $key, $value);
}
die;
}
I am posting product type from front end programatically. It is inserting product type into the database but not returning the post id. Instead it gives me this error "Call to a member function get_product() on a non-object in /srv/data/web/vhosts/www.wiine.me/htdocs/devbeta/wp-content/plugins/woocommerce/woocommerce-core-functions.php on line 32".
get_product() is woocommerce function may be hooked with wp_insert_post( $wine_post ) . it gives error after wp_insert_post funciton. so i can not add meta for this post.
Can anyone tell me why?

Resources