Sunday, March 29, 2015

Create post programatically and assigned category to posts (If category & Posts not exists it will create and assign to that posts).


$new_post = array(
'post_name' => sanitize_title($data['Handle']), // Slug
'post_title' => convert_chars($data['Title']),
'post_content' => wpautop(convert_chars($data['Body (HTML)'])),
'post_status' => 'publish',
'post_type' => 'post',
//'post_category' => array($new_cat_ID)
);

if($id = post_exists($new_post['post_title'], $new_post['post_content']))
{
$new_post['ID'] = (int)$id;
$id = wp_update_post($new_post);
if ( is_wp_error( $id ) )
{
return $id;
}
if (!$id)
{
$output .= "Couldn't get post ID";
return;
}

foreach($data as $key => $value)
{
update_post_meta($id, sanitize_user('Shopify '.$key), esc_attr($value));
}
$output .= 'Updated !'. ' <a href="'.get_permalink($id).'">View '.$data['Title'].'</a>';
}
else
{
$id = wp_insert_post($new_post);
}

$arrCategories = explode(',', $data['Categories']);
if(count($arrCategories) > 0)
{
global $wpdb;
foreach($arrCategories as $key => $category_name)
{
$slug = strtolower( str_ireplace( ' ', '-', $category_name ) );
$sqlTermQuery = "SELECT * FROM wp_terms WHERE slug = '".$slug."'";
$arrTermsArray = $wpdb->get_results($sqlTermQuery);
if(count($arrTermsArray) <= 0)
{
$sqlInsertTerm = "INSERT INTO wp_terms SET name = '".ucfirst($category_name)."',slug = '".$slug."'";
$wpdb->query($sqlInsertTerm);
$lastid = $wpdb->insert_id;
$sqlInsertTermTexonomy = "INSERT INTO wp_term_taxonomy SET term_id = '".$lastid."',taxonomy = 'category'";
$arrTexonomy[] = $wpdb->get_results($sqlInsertTermTexonomy);
$lasttexonomyid = $wpdb->insert_id;
$arrCategories_ids[] = $lastid;
}
else
{
$sqlTermQuery = "SELECT * FROM wp_terms WHERE slug = '".$slug."'";
$arrTermsArray = $wpdb->get_results($sqlTermQuery);
$intTermid = $arrTermsArray[0]->term_id;

$sqlTexonomy = "SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE term_id = '".$intTermid."' AND taxonomy = 'download_category'";
$arrTaxonomy = $wpdb->get_results($sqlTexonomy);
if(count($arrTaxonomy) > 0)
{
$lasttexonomyid = $arrTaxonomy[0]->term_taxonomy_id;
}
else
{
$sqlInsertTermTexonomy = "INSERT INTO wp_term_taxonomy SET term_id = '".$intTermid."',taxonomy = 'download_category'";
$arrTexonomy[] = $wpdb->get_results($sqlInsertTermTexonomy);
$lasttexonomyid = $wpdb->insert_id;
}
}

if($lasttexonomyid >0 && $id > 0)
{
$sqlInsertTerm = "INSERT INTO wp_term_relationships SET object_id = '".$id."',term_taxonomy_id = '".$lasttexonomyid."'";
$wpdb->query($sqlInsertTerm);
}
}
}

No comments:

Post a Comment

Please mention your comments.......