Wordpress XML-RPC post to a specific category - php

I've been trying for quite a long time and still it posts only as "Uncategorized",
In the documentation it's stated to use integer value as category ID, but that doesn't work. I've also tried writing category name as it is and in lowercase and also entering slug. According to documentation I'm doing everything right, but it still doesn't work!
wp.newPost and since it uses wp_insert_post().
public function create_post( $title, $body )
{
$title = htmlentities( $title, ENT_NOQUOTES, 'UTF-8' );
$content = array(
'post_category' => array( 18 ), // my category id
'post_type' => 'post',
'post_status' => 'pending',
'post_title' => $title,
'post_content' => $body,
'comment_status' => 'closed',
);
$params = array( 0, $this->username, $this->password, $content );
return $this->send_request( 'wp.newPost', $params );
}

Hey I've recently started using the new API.
You should use the terms_names parameter in your XML-RPC request as stated in the new docs:
http://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost
Example:
Your code should be changed to look something like this.
public function create_post( $title, $body )
{
$title = htmlentities( $title, ENT_NOQUOTES, 'UTF-8' );
$content = array(
'post_type' => 'post',
'post_status' => 'pending',
'post_title' => $title,
'post_content' => $body,
'terms' => array('category' => array( 18 ) ),
'comment_status' => 'closed',
);
$params = array( 0, $this->username, $this->password, $content );
return $this->send_request( 'wp.newPost', $params );
}
I have one problem with this API method however, the Post ID is not returned only a false boolean value. Let me know if you have any luck with inserting categories and if you manage to receive the POST ID.

Thanks, this is a life saver! If you need to provide tags for your post, you can pass them in array using tags_input property, like this:
$content['tags_input'] = "action, adventure, thriller";
If you need to pass in a specific time stamp, you should use the following format
D, d M Y H:i:s +0000
and pass it using the post_date or post_date_gmt property:
$content['post_date_gmt | post_date'] = date("D, d M Y H:i:s +0000", strtotime($your_specific_date_and_time));
Hope it helps someone in the future!

Related

Create a 2 different Posts in 2 different custom post type after function

I am trying to create a 2 different posts in 2 different post types. What i am trying to achieve is to have 2 unique posts, and if a button is clicked twice, it shouldn't create the post again.
<?
$custom_title = $company_name . '-' . $formindex;
$args = array(
'post_type' => 'dogovori',
'post_title' => $custom_title,
'post_name' => $company_name,
'post_status' => 'publish',
'post_content' => $content_dogovor,
);
$post_id = post_exists($custom_title) or wp_insert_post($args);
$args1 = array(
'post_type' => 'svidetelstva',
'post_title' => $custom_title,
'post_name' => $company_name,
'post_status' => 'publish',
'post_content' => $content_dogovor,
);
$post_id1 = post_exists($custom_title) or wp_insert_post($args1);
This is what i am using as a code. It works perfectly and creates the post only in 'dogovori'. What i want is to create at the same time in 'svidetelstva' as well.
The function post_exists does not pay any attention to your post type. So first you are inserting a new post with a custom title. When you check if a post exists the second time, it finds the first post you inserted.
Please reference this SA answer to check if a specific custom post exists with a title:
https://wordpress.stackexchange.com/a/300151

How to create a wordpress plugin that will create and update custom post types from an external json feed

I have created two custom post types - Seasons and Competitions what I would like to do is use data from an external api to make a wordpress plugin that will create and update these posts, I have made several attempts but so far failing to get this to work a sample of the api is:
{"id":15,"startDate":"14-06-2014","endDate":"23-07-2015","competition":{"id":43,"name":"Champions League"},"sponsor":{"id":12,"name":"UEFA","description":"Uefa"}}``
and the code so far for the plugin:
function add_posts()
{
$season_request = 'https://somedomain/api/info';
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( user . ':' . password)
)
);
$season_response = wp_remote_get( $season_request, $args );
$season_data = json_decode($season_response['body']);
if(! $season_data)
return false;
$query = array(
'meta_query' => array(
array(
'key' =>'season_id',
'value' => $season_data->id
)
),
'post_type' => 'seasons',
'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit'),
'posts_per_page' => 1
);
$season = get_posts($query);
$season_id = '';
if($season)
$season_id = $season[0] -> id;
$season_post = array
(
'ID' => $season_id,
'post_title' => $season_data -> startDate . endDate . 'test',
'post_type' => 'seasons',
'post_author' => 1,
'post_status' => ($season) ? $season[0] -> post_status : 'publish'
);
$season_id = wp_insert_post($season_post);
}
I'm relatively new to php(not to coding) so it may be something glaringly obvious that I can't see. I thought that this would be something that there would be some detailed documentation on but if there is it seems to be hidden from me pretty well. Any help or pointers in the right direction would be really appreciated.
Thanks
The correct way to call the external api was as follows:
$data_request = 'https://yoururlforapihere/api/data';
$username = 'user';
$password = 'password';
$headers = array( 'Authorization' => 'Basic ' . base64_encode("$username:$password" ) );
$data_response = wp_remote_get( $data_request, array( 'headers' =>$headers, 'sslverify' => false));
Once the data was coming in properly the rest became more straightforward.

Adding tag input in post form

So, I have following form in my plugin for post upload (wordpress):
if(empty($_POST['post_id'])){
$post = array(
'post_content' => 'Dummy Content',
'post_title' => 'Dummy Title',
'post_status' => 'inherit',
'post_type' => 'post'
);
$post_id = wp_insert_post( $post, true );
}else{
$post_id = $_POST['post_id'];
}
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$filename = rand() . '' . $files['name'][$key];
$file = array(
//Here goes other irrelevant code
);
$upload_overrides = array( 'test_form' => false );
$image_path[] = array(
'image_path' => $upload_dir['url'] . '/' . $filename,
'meta_key' => 'upload_image',
'meta_value' => $upload_dir['url'] . '/' . $filename,
'post_id' => $post_id
);
add_post_meta($post_id, 'upload_image', $upload_dir['url'] . '/' . $filename );
}
}
echo json_encode($image_path);
exit;
Above function adds an image as a post with dummy contents such as title/description etc.
Now, if I want to update the content, then I can do so by following:
global $wpdb;
$tags = $_POST['rh_tags'];
if(!empty($_POST['post_id'])){
$data = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['content'],
'tags_input' => $tags,
'post_status' => 'publish'
);
$where = array('ID' => $_POST['post_id']);
$update = $wpdb->update($wpdb->prefix . 'posts' , $data, $where, $format = null, $where_format = null );
}else{
$post = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['content'],
'post_status' => 'publish',
'tags_input' => $tags,
'post_type' => 'post'
);
wp_insert_post($post);
}
echo 'success';
exit;
Here I added 'tags_input' => $tags, to add a post tag.
Here is current situation:
1. No image selected: in the input field (a form with simple input field with title, description and tag), if I add something to the tag input while there is no image selected, then the post is created properly with the tag.
2. Image selected: if an image is selected, then with the tag input, it does not create the post at all.
I tried to add 'tags_input' => $tags, in the very first function, but that did not work either.
Can someone point out what change I need to make in my first function?
Suggest you add some var_dump statements if this is still a problem. When followed by an exit; statement, this will immediately show the data in the object.
I'd want to look at the state of the data within each if/then statement and the expected data in each function.
Of course, the data before and after your image is created/uploaded. Then I would expect the problem to become visible.
So generally, I'd do the following to debug the issue.
At various places put the following debugging code and you may also add the different critical variables using a comma separator in the var_dump function:
var_dump($_POST);
exit;
You also should consider using better variable names because the code
is more confusing to debug than it needs to be. The variable names are
not consistent even within a single if/then loop for example in the
second function you mention $data and then $post.

WordPress Getting post data for Post Grid of Visual Composer

I'm using Visual Composer in WordPress and I want to make a custom Post Grid. But the default elements that the post grid supplies are not enough. I want to show the author of the post, the number of comments it has, the category it has and the Tags it has as well. I'm not really familiar with Visual Composer, but I need a point in the right direction for me to get this data? What can I do? I've search their documents but with no luck. If I need to move around the php code I would like to know what I'm moving around is the right thing. Any ideas? If you need any more information please do ask :D
Thanks in advance for the help.
If anybody is still looking to find out how to to get the id in a post grid or create a specific widget for the grid you can use the following snippet I creatd for adding an icon before the post title. You will see inside the first function you can call $post-ID for use on any query.
//** Case Study Title Block Shortcodes ***********
//********************************
add_filter( 'vc_gitem_template_attribute_case_study_title','vc_gitem_template_attribute_case_study_title', 10, 2 );
function vc_gitem_template_attribute_case_study_title( $value, $data ) {
extract( array_merge( array(
'post' => null,
'data' => '',
), $data ) );
$atts_extended = array();
parse_str( $data, $atts_extended );
$atts = $atts_extended['atts'];
// write all your widget code in here using queries etc
$title = get_the_title($post->ID);
$link = get_permalink($post->ID);
$terms = get_the_terms($post->ID, 'case_categories');
$output = "<h4 class=\"case-title\">". get_the_icon($terms[0]->term_id) . $title ."</h4>";
return $output;
}
add_filter( 'vc_grid_item_shortcodes', 'case_study_title_shortcodes' );
function case_study_title_shortcodes( $shortcodes ) {
$shortcodes['vc_case_study_title'] = array(
'name' => __( 'Case Study Title', 'sage' ),
'base' => 'vc_case_study_title',
'icon' => get_template_directory_uri() . '/assets/images/icon.svg',
'category' => __( 'Content', 'sage' ),
'description' => __( 'Displays the case study title with correct icon', 'sage' ),
'post_type' => Vc_Grid_Item_Editor::postType()
);
return $shortcodes;
}
add_shortcode( 'vc_case_study_title', 'vc_case_study_title_render' );
function vc_case_study_title_render($atts){
$atts = vc_map_get_attributes( 'vc_case_study_title', $atts );
return '{{ case_study_title }}';
}
I got the same issue; here is how I solve it:
According to Visual Composer documentation: https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
When you add the code below to functions.php, a new component will be added in your custom grid builder (in my example the name will be "Author"). There are a number of values you can get by post data template variable function and one of it not the name of the author but their ID (that's sad but at least you can use this value to get the author name).
The value is 'post_author' => ID of the author (for example '1')
Here is the function where I get the post author and display it (if author component was added to your custom grid in "custom grid builder"). Put it in functions.php of your child theme:
add_filter( 'vc_grid_item_shortcodes', 'my_module_add_grid_shortcodes' );
function my_module_add_grid_shortcodes( $shortcodes ) {
$shortcodes['vc_post_id'] = array(
'name' => __( 'Author', 'my-text-domain' ),
'base' => 'vc_post_id',
'category' => __( 'Content', 'my-text-domain' ),
'description' => __( 'Show current post author', 'my-text-domain' ),
'post_type' => Vc_Grid_Item_Editor::postType(),
);
return $shortcodes;
}
// output function
add_shortcode( 'vc_post_id', 'vc_post_id_render' );
function vc_post_id_render() {
$nn = '{{ post_data:post_author }}'; // usage of template variable post_data with argument "post_author"
return get_the_author($nn);
}
There is a little problem. It works but get_the_author is a deprecated function in WordPress. I'd appreciate any suggestions to make it more modern or if you name other alternatives please suggest.
Also, here is the list of available variables of vc_post_id_render from docs. Here they are:
WP_Post::__set_state(array(
'ID' => 69,
'post_author' => '1',
'post_date' => '2015-04-29 14:15:56',
'post_date_gmt' => '2015-04-29 14:15:56',
'post_content' => 'Your post content',
'post_title' => 'Your post title',
'post_excerpt' => '',
'post_status' => 'publish',
'comment_status' => 'open',
'ping_status' => 'open',
'post_password' => '',
'post_name' => 'post name',
'to_ping' => '',
'pinged' => '',
'post_modified' => '2015-06-17 11:18:41',
'post_modified_gmt' => '2015-06-17 11:18:41',
'post_content_filtered' => '',
'post_parent' => 0,
'guid' => 'http://wp.master/?p=69',
'menu_order' => 0,
'post_type' => 'post',
'post_mime_type' => '',
'comment_count' => '0',
'filter' => 'raw',
'filter_terms' =>
array (
),
))
this is your response
https://kb.wpbakery.com/docs/developers-how-tos/adding-custom-shortcode-to-grid-builder/
at Template variables usage
Exemple, in visual composer template you can use {{ post_date:ID }} to show post ID. I don't know how show tag.

Wordpress and wp_insert_post not working

i'm doing an webapp that works with a wordpress website.
Until yesterday all works like a charm, but from today, when i save the post on wordpress db, it now not working...
Not give me error (php error or wordpress error), but simply a white page.
This is my full code:(sorry for many commented lines and echo, but i'm testing)
The important part:
// Create post object
$my_post = array(
'post_title' => $article_title,
'post_name' => $article_title,
'post_content' => $article_content,
'post_status' => 'pending',
'post_author' => 1
);
// Insert the post into the database
wp_insert_post($my_post, TRUE);// try first time
$post_status = "pending";
$post_type = "post";
$post_parent = "0";
$post_ID = (int) $wpdb->insert_id;
echo $post_ID; die;
Yesterday with a simple wp_insert_post(my_post); all worked fine, today (of course i think i edited some files...or i don't now), not works more and not give me error.
What do you think ?
Thank you, really!
EDIT: The problem was that i not insert post_category and wp need it!
You can capture the $post_id with the wp_insert_post() function...
$post_ID = wp_insert_post($my_post, TRUE);// try first time
Then you can dump out the $post_ID variable to get the ID or the error.
var_dump($post_ID);
add_action( 'init', 'my_func' );
function my_func() {
$my_post = '';
if( get_page_by_title($article_title,'OBJECT','post') == NULL )
$my_post= array(
'post_title' => $article_title,
'post_name' => $article_title,
'post_type' => 'post',
'post_content' => $article_content,
'post_status' => 'pending',
'post_author' => 1
);
$post_id = wp_insert_post( $my_post );
echo 'Post ID - '.$post_id;
}

Categories