PHP merge arrays and send through wp_insert_post() - php

I am trying to merge the following arrays.
I want this result:
foreach( $datas as $data ) {
$my_post = array(
'post_title' => $title['title_value'],
'post_status' => 'pending',
'post_type' => $type['type_value'],
'post_author' => $author['author_value'],
);
wp_insert_post( $my_post );
}
My data:
$title = title1,title2,,title4,title5 // 5 datas separated with coma
$type = type1,type2,type3,type4,, // 5 datas separated with coma
$author = ,author2,author3,author4,author5 // 5 datas separated with coma
What I have done:
$datas = array(
'title' => explode( ",", $title ),
'type' => explode( ",", $type ),
'author' => explode( ",", $author ),
);
foreach( $datas as $data ) {
// foreach( $data as $d ) {
// }
}
Does anybody know how to do this?
Hope you can understand the question. Thank you in advance.

If your all data(title,type and author) have same data count you can use this way
$title_array = explode(',', $title);
$type_array = explode(',', $type);
$author_array = explode(',', $author);
if (count($title_array) > 0)
{
foreach ($title_array as $title_index => $title_value)
{
$my_post = array(
'post_title' => $title_value,
'post_status' => 'pending',
'post_type' => $type_array[$title_index],
'post_author' => $author_array[$title_index],
);
wp_insert_post($my_post);
}
}

Related

How to export category name and category link in wordpress json

all queries work except category name and category link, if I use "get_the_category()" it shows several things I don't need, like "category_count" , "category_description" etc.
and i need to know how to separate jsons by post category
this is my code
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
$posts = array();
while( $query->have_posts() ) : $query->the_post();
$posts[] = array(
'id' => get_the_ID(),
'date' => get_the_date(),
'title' => get_the_title(),
'link' => get_the_permalink(),
'image' => get_the_post_thumbnail_url(),
'category' => get_the_category ( 'cat_name' ),
'categoryLink' => get_category_link ( $category_id )
);
endwhile;
wp_reset_query();
$data = json_encode($posts);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen( $save_path , "w" );
fwrite($f , $data);
fclose($f);
}
add_action( 'save_post', 'export_posts_in_json' ); ```
get_the_category requires a post id (or boolean false) - See: https://developer.wordpress.org/reference/functions/get_the_category/
get_category_link requires an integer or category object - See: https://developer.wordpress.org/reference/functions/get_category_link/
Check your parameters and see if that helps.

WordPress – output categories, posts and images to JSON

I'm trying to recreate a JSON file with a specific structure and only getting so far as I'm not that familiar with PHP.
I'd like to list all used/non-empty categories, then all posts within each category and then all images/other details used in each post.
I'm not sure how the code should look in the loop. I'd need the JSON to be exactly like below (brackets) as I'm feeding it to a D3 script:
{
"project": "Farm", // website name
"about": "What we have on the farm.",
"categories": [ //post categories
{
"slug": "fruits",
"title": "Fruits",
"description": "All about fruits.",
"posts": [ // all posts within a category
{
"slug": "apples",
"title": "Apples",
"excerpt": "Apple trees and fruits.",
"tags": "tree, apple",
"post_images": [
{
"id": 25,
"title": "Apple trees.",
"filename": "apple-trees.jpg",
"desc": "Rows of apple trees.",
"tags": ""
},
(...)
The PHP script so far (in functions.php):
function export_to_json() {
global $post;
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$posts = array();
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$query = new WP_Query( $post_args );
while ( $query->have_posts() ): $query->the_post();
$posts[] = array(
'categories' => [
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => [
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'images' => get_attached_media( 'image' ),
'tags' => get_tags()
]
]
);
endwhile;
wp_reset_query();
}
$data = json_encode($posts, JSON_PRETTY_PRINT);
$upload_dir = wp_get_upload_dir();
$file_name = date('Y-m-d') . '.json';
$save_path = $upload_dir['basedir'] . '/' . $file_name;
$f = fopen($save_path, "w");
fwrite($f, $data);
fclose($f);
}
add_action('save_post', 'export_to_json');
The script is wrong because categories get repeated for each post and I'd like all posts within a category to be properly nested.
Any help with this would be much appreciated. Thanks.
Here you go:
function export_to_json() {
global $post;
$categories = array();
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$cats = get_categories( $cat_args );
foreach( $cats as $cat ) {
$post_args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'category__in' => $cat->term_id
);
$get_posts = array();
$posts = get_posts( $post_args );
foreach($posts as $post){
$tags = get_the_tags($post->ID);
$i = 0;
$tag_names = '';
$post_images = array();
if( $tags) {
foreach( $tags as $tag ) { $i++;
$comma = $i == count($tags) ? '' : ', ';
$tag_names .= $tag->name . $comma;
}
}
$images = get_post_gallery($post->ID, false);
if($images){
$image_ids = explode(",", $images['ids']);
foreach ($image_ids as $image ){
$img = wp_prepare_attachment_for_js($image);
$post_images[] = array(
"id" => $img['id'],
"title" => $img['name'],
"filename" => $img['filename'],
"desc" => $img['description'], //Pulls the image description
'tags' => $tag_names
);
}
}
$get_posts[] = array(
'slug' => $post->post_name,
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'tags' => $tag_names,
'post_images' => $post_images
);
}
$categories[] = array(
'slug' => $cat->slug,
'title' => $cat->cat_name,
'description' => $cat->description,
'posts' => $get_posts
);
}
$output = array(
'project' => get_bloginfo('name'),
'about' => get_bloginfo('description'),
'categories' => $categories
);
$data = json_encode($output, JSON_PRETTY_PRINT);
}

WordPress: Pagination for custom array

I have this snippet for creating a list of users sorted by the highest post views.
But I'm wondering of how can I create pagination for a custom array like that.
$topuser = array();
$avatar_size = 100;
$args = array(
'role__in' => array( 'contributor', 'author' ),
'hide_empty' => '1'
);
$users = get_users( $args );
foreach ( $users as $user ) {
$query = get_posts(
array(
'author' => $user->ID,
'cat' => '3',
'numberposts' => -1,
'post_type' => 'post',
)
);
$counter = 0;
$post_count = count_user_posts( $user->ID );
if ( ! $post_count ) {
continue;
}
// get each post of a user
foreach ( $query as $post ){
$views = absint( get_post_meta( $post->ID, 'post_views_count', true ) );
$counter += $views;
}
$topuser[] = array(
'id' => $user->ID,
'views' => $counter,
);
wp_reset_query();
}
// function to sort array based on views count
function sortViews( $a, $b ) {
return $b['views'] - $a['views'];
}
usort( $topuser, 'sortViews' ); // sort the array
$output = $topuser;
Thanks in advance!

Query by part of string in custom field

I am trying to query for a string if present in a custom field.
e.g. Within the custom field I have a value like: Milano romani and If I have a string Milano from GET, I should find it. But the following gives me all posts even if no string match in the custom field
<?php
$myTerm = $_GET['cityName'];
$catIds = array();
$args = get_posts(
array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'usp-custom-23',
'value' => $myTerm,
'compare' => 'LIKE'
)
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$id = get_the_ID();
array_push($catIds, $id);
}
$catIds = implode( ", ", $catIds );
if(count($catIds) > 0){
$arrayFUllCity = "fullCity";
} else {
$arrayFUllCity = "empty";
}
}
var_dump($catIds);
?>

Duplication of message when adding to DB in wordpress

When i try to add one post to db using wp_insert_post() in db added two posts:
Ajax request:
/wp-admin/admin-ajax.php?action=getchats&chat_type=all-chat&last_msg=110&add_msg=true&chat_message=helloworlds
action for this:
add_action( 'wp_ajax_getchats', 'getchats');
function getchats(){
if (!isset($_GET['last_msg'])||(!is_numeric($_GET['last_msg'])||(!isset($_GET['chat_type'])))){
die(json_encode(array('error' => 'no_latest')));
}
$cat_id = get_cat_ID($_GET['chat_type']); //the categories name
if ((isset($_GET['add_msg']))&&(isset($_GET['chat_message']))){
$user_id = get_current_user_id();
$description = $_GET['chat_message'];
$title = $description;
if (strlen($title)>20){
$title = mb_substr($title, 0, 20, 'UTF-8');
}
$my_post = array(
'post_content' => $description,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'chatmsg',
'post_author' => $user_id,
'post_category' => array($cat_id)
);
wp_insert_post($my_post);
}
$args=array(
'numberposts' => 3,
'orderby' => 'ID',
'category' => $cat_id,
'post_type' => 'chatmsg',
'post_status' => 'publish',
);
$messages = [];
$posts = get_posts($args);
die(json_encode($posts));
foreach( $posts as $post ){
if ($post->ID > $_GET['last_msg']){
$row = array(
'id' => $post->ID,
'message'=>$post->post_content,
'author'=>$post->post_author,
'date'=>$post->post_date,
);
$message[] = $row;
}
}
die(json_encode(array('error' => 'ok', 'messages'=> $messages)));
}
Why am i using only one wp_insert_post but receive two post?
UPD: Need use wp_doing_ajax for it. Thanks for answer Maxim Sarandi.
if( wp_doing_ajax() ) {
add_action('wp_ajax_getchats', 'getchats');
function getchats()
{
//some code
}
}
Maybe this or this might help you.
And can i give you a few recommendation to your code style?
First - use $_POST for similar queries.
Second - stop use die(wp_send_json()). Inside wp_send_json already present die(); Just use wp_send_json_error() for error response or wp_send_json_success(); or wp_send_json()
Third - use nonces and check_ajax_referer();
Fourth - stop cloning not needed brackets.

Categories