Plugin Development - wp insert post not working - wordpress

I am new to plugin development for WP. I have a problem with wp_insert_post from the plugin file, tested running this plugin php file, and all the code before the wp_insert_post is fine, but once it jumps on wp_insert_post nothing happens after, stuck at 'Test15'. Tested running the insert post part of the code from test page within the theme folder and it worked. Not sure what is the problem here. Please see the code below.
function db_importer_insert_properties($properties, $category, $user_id, $post_type) {
echo 'Test9<br>';
$result = true;
echo 'Test10<br>';
if($properties) {
echo 'Test11<br>';
if(count($properties) > 0) {
echo 'Test12<br/>';
print_r($properties);
echo '<br/>';
$count = 0;
foreach($properties as $property) {
echo 'Test13<br/>';
$address =$property['address'] ; //get title
$building=$address['streetNumber'];
$street=$address['street'];
$suburb=$address['suburb'];
$state=$address['state'];
$postcode=$address['postcode'];
$title=$building. ' ' .$street.', '.$suburb.', '.$postcode.', '.strtoupper($state);
//test post
$new_post = array(
'post_title' => 'My post10 ',
'post_content' => 'This is my post10 ',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => 'uncategorized'
);
echo 'Test14<br/>';
print_r($new_post);
echo '<br/>';
echo 'Test15<br/>';
wp_insert_post($new_post);
echo 'Test16<br>';
if($post_id != 0) {
add_post_meta($post_id, "_bathrooms", esc_attr($property['features']['bathrooms']));
add_post_meta($post_id, "_bedrooms", esc_attr($property['features']['bedrooms']));
if(is_array($property['images'])) {
add_post_meta($post_id, "_images", esc_attr(implode("\n", $property['images'])));
}
else {
feedback("Post ID was 0");
}
feedback("added property $title with post_id $post_id");
$count++;
}
else {
feedback("post was failed to add");
}
}
feedback("Added $count properties");
}
else {
feedback("No properties to add.");
}
}
else {
feedback("No properties were selected");
$result = false;
}
return $result;
}

You forgot to declare your $post_id variable. Use the following:
$post_id = wp_insert_post( $new_post, true );
This will return the post ID on success or a WP error on failure.
Use print_r( $post_id ) to check the result.

Related

How to create a shortcode for Woocommerce view-order template?

I want to create a shortcode for view-order.php template, which is located in my child theme /woocommerce/myaccount/view-order.php or can be accessed via url /my-account/view-order/{id}/ I've read this article How to create a shortcode for custom page template? and adjusted the code as below:
function view_order_shortcode() {
ob_start();
get_template_part('view-order');
return ob_get_clean();
}
add_shortcode( 'view_order_shortcode', 'view_order_shortcode' );
Then I insert <?php echo do_shortcode("[view_order_shortcode]"); ?> into a template where I want it to display but it's not working.
I read this article as well Woocommerce - How to show Order details (my-account) on a separate page but this one talks about my-orders.php The code below works fine.
function woocommerce_orders() {
$user_id = get_current_user_id();
if ($user_id == 0) {
return do_shortcode('[woocommerce_my_account]');
}else{
ob_start();
wc_get_template( 'myaccount/my-orders.php', array(
'current_user' => get_user_by( 'id', $user_id),
'order_count' => $order_count
) );
return ob_get_clean();
}
}
add_shortcode('woocommerce_orders', 'woocommerce_orders');
However, I've adjusted it to bellow but it's not working. Any suggestion?
function woocommerce_orders() {
$user_id = get_current_user_id();
if ($user_id == 0) {
return do_shortcode('[woocommerce_my_account]');
}else{
ob_start();
wc_get_template( 'myaccount/view-order.php', array(
'current_user' => get_user_by( 'id', $user_id),
) );
return ob_get_clean();
}
}
add_shortcode('woocommerce_orders', 'woocommerce_orders');
view-order.php template requires two parameters to get it to work.
order
order_id
In your example, this should work.
function woocommerce_view_order($params) {
$order_id = $params['order_id']; // get order id from shortcode params
$user_id = get_current_user_id();
if ($user_id == 0) {
return do_shortcode('[woocommerce_my_account]');
}else{
ob_start();
wc_get_template( 'myaccount/view-order.php', array(
'order' => wc_get_order($order_id), // add this line
'order_id' => $order_id //add this line
) );
return ob_get_clean();
}
}
add_shortcode('woocommerce_view_order', 'woocommerce_view_order');
Then, apply the shortcode with an order id:
Example: [woocommerce_view_order order_id=103]

Wordpress unique checkbox

I have created a custom field "headline" in posts that is handled by a checkbox. Now I want that when the post is saved and the checkbox is checked, all "headline" checkboxes are emptied in the other posts. If this works correctly there should only be one other post with that checkbox checked.
function createHeadlineField()
{
$post_id = get_the_ID();
if (get_post_type($post_id) != 'post') {
return;
}
$value = get_post_meta($post_id, '_headline_field', true);
wp_nonce_field('headline_nonce_'.$post_id, 'headline_nonce');
?>
<div class="misc-pub-section misc-pub-section-last">
<label><input type="checkbox" value="1" <?php checked($value, true, true); ?> name="_headline_field" /><?php _e('This post is the top Story', 'pmg'); ?></label>
</div>
<?php
}
function saveHeadlineField($post_id)
{
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (
!isset($_POST['headline_nonce']) ||
!wp_verify_nonce($_POST['headline_nonce'], 'headline_nonce_'.$post_id)
) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
if (isset($_POST['_headline_field'])) {
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
} else {
delete_post_meta($post_id, '_headline_field');
}
}
Has anybody a clue how to do that? I guess I have to query the posts for posts with _headline_field values and delete these before updating the actual post.
thx
so if u want to query the posts with the metakey Headline u can do something like that:
$posts = array();
$query = new WP_Query(array('meta_key' => Headline, 'meta_value'=>YOURVALUE, 'posts_per_page' => LIMIT (-1 for endless)))
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$posts[] = $query->post;
}
wp_reset_postdata();
}
return $posts;
I tried to do it like that:
if (isset($_POST['_headline_field'])) {
//query posts with custom field selected
$args = array ( 'meta_key' => '_headline_field', 'meta_value' => '1', LIMIT -1 );
$headline_query = new WP_Query( $args );
if ( have_posts() ):
while ( have_posts() ) :
$headline_query->the_post();
$headline_query->delete_post_meta(get_the_ID(), '_headline_field');
endwhile;
endif;
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
Ok, found a solution.
I just used the "delete_post_meta_by_key()" function to erase alle post meta with the key _headline_field before writing the new value into the DB.
if (isset($_POST['_headline_field'])) {
delete_post_meta_by_key( '_headline_field' );
update_post_meta($post_id, '_headline_field', $_POST['_headline_field']);
}

How to list all users of posted in wordpress

$args = array(
'orderby' => 'display_name'
);
$wp_user_query = new WP_User_Query($args);
$authors = $wp_user_query->get_results();
if (!empty($authors))
{
echo '<ul>';
foreach ($authors as $author)
{
$author_info = get_userdata($author->ID);
echo '<li>'.$author->ID.' '.$author_info->first_name.' '.$author_info->last_name.'</li>';
}
echo '</ul>';
} else {
echo 'No authors found';
}
I'm using post filter by post author. Above code displays all the users so need to display only authors who posted in the blog.
just like wp_list_authors() function but i need to get the author id intead of author name. because I need to create a dropdown list. While someone change the option, then I need to get the post by that author in AJAX
Update 1:
Hope this help:
$posted = get_posts([
'post_type' => 'your_custom_post_type',
]);
$author_ids = [];
foreach ($posted as $post) {
$author_ids[] = $post->post_author;
}
$author_ids = array_unique($author_ids);
if (!empty($author_ids) )
{
echo '<ul>';
foreach ($author_ids as $user_id)
{
$author_info = get_userdata($user_id);
echo '<li>'.$user_id.' '.$author_info->first_name.' '.$author_info->last_name.'</li>';
}
echo '</ul>';
} else {
echo 'No authors found';
}
Make sure to change post_type to your post type and each user has both first_name and last_name.
There's a missing argument on Codex reference: has_published_posts.
$args = [
'orderby' => 'display_name',
'has_published_posts' => true
];
$authors = new WP_User_Query($args);
...
It's better to look for inside class file because info on Codex is not always up-to-date.

wordpress metabox merge select + input text

I'm going to break my brain..
I've created a new metabox for my custom post type "book".
I'm using a lot of different type of fields like input text, checkbox, select, textarea, taxonomy select and repeatable and everything work great!
But now I'd like to do a more difficult step..
Is it possible to do a repeatable field with 2 fields inside it?
I would like have a select and an input text near it.. inside the select admin can choose the shop (es. Ibs or Amazon) and in the input field he can write the url for sell the book.
This is my code:
/* META Book */
function add_mycustom_meta_box() {
add_meta_box(
'custom_meta_box',
'Info book',
'show_custom_meta_box', // $callback
'product',
'normal',
'high');
}
// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
array(
'label' => 'Link vendita',
'desc' => 'Inserisci l url dei siti esterni',
'id' => $prefix.'repeatable',
'type' => 'repeatable',
'options' => array(
'amazon' => array(
'label' => 'Amazon',
'value' => 'amazon'
),
'ibs' => array(
'label' => 'Ibs',
'value' => 'ibs'
)
)
)
);
// Callback
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// Build metabox
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get value of this field if it exists for this post
$meta = get_post_meta($post->ID, $field['id'], true);
// begin a table row with
echo '<tr>
<th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
<td>';
switch($field['type']) {
// if repeatable
case 'repeatable':
echo '<a class="repeatable-add button" href="#">+</a>
<ul id="'.$field['id'].'-repeatable" class="custom_repeatable">';
$i = 0;
if ($meta) {
foreach($meta as $row) {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis or amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// end select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="'.$row.'" size="30" data-shop="'.$option.'" />
<a class="repeatable-remove button" href="#">-</a></li>';
$i++;
}
} else {
echo '<li><span class="sort hndle">|||</span>';
// Select ibis o amazon
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $row == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select>';
// Fine select
echo '<input type="text" name="'.$field['id'].'['.$i.']" id="'.$field['id'].'" value="" size="30" />
<a class="repeatable-remove button" href="#">-</a></li>';
}
echo '</ul>
<span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>';
}
// Save the Data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verify nonce
if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop through fields and save the data
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
}
add_action('save_post', 'save_custom_meta');
The repeatable field generate an array and it is ok, but what I can do to store the select value also?
Hope someone can help me
Thanks
I'm sure you can put in dynamic fields into custom Metaboxes inside the edit screen of any post type.
I build this for the Language Field Plugin into the admin page on http://wordpress.org/plugins/language-field/
I was relying on this example
http://www.mustbebuilt.co.uk/2012/07/27/adding-form-fields-dynamically-with-jquery/
Generally take these steps
Add custom Meta box with this example
http://codex.wordpress.org/Function_Reference/add_meta_box#Examples
when it comes to these lines
$mydata = sanitize_text_field( $_POST['myplugin_new_field'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_my_meta_value_key', $mydata );
loop thru the fields created with example above.

Wordpress custom metabox input value with AJAX

I am using Wordpress 3.5, I have a custom post (sp_product) with a metabox and some input field. One of those input (sp_title).
I want to Search by the custom post title name by typing in my input (sp_title) field and when i press add button (that also in my custom meta box), It will find that post by that Title name and bring some post meta data into this Meta box and show into other field.
Here in this picture (Example)
Search
Click Button
Get some value by AJAX from a custom post.
Please give me a example code (just simple)
I will search a simple custom post Title,
Click a button
Get the Title of that post (that i search or match) with any other post meta value, By AJAX (jQuery-AJAX).
Please Help me.
I was able to find the lead because one of my plugins uses something similar to Re-attach images.
So, the relevant Javascript function is findPosts.open('action','find_posts').
It doesn't seem well documented, and I could only found two articles about it:
Find Posts Dialog Box
Using Built-in Post Finder in Plugins
Tried to implement both code samples, the modal window opens but dumps a -1 error. And that's because the Ajax call is not passing the check_ajax_referer in the function wp_ajax_find_posts.
So, the following works and it's based on the second article. But it has a security breach that has to be tackled, which is wp_nonce_field --> check_ajax_referer. It is indicated in the code comments.
To open the Post Selector, double click the text field.
The jQuery Select needs to be worked out.
Plugin file
add_action( 'load-post.php', 'enqueue_scripts_so_14416409' );
add_action( 'add_meta_boxes', 'add_custom_box_so_14416409' );
add_action( 'wp_ajax_find_posts', 'replace_default_ajax_so_14416409', 1 );
/* Scripts */
function enqueue_scripts_so_14416409() {
# Enqueue scripts
wp_enqueue_script( 'open-posts-scripts', plugins_url('open-posts.js', __FILE__), array('media', 'wp-ajax-response'), '0.1', true );
# Add the finder dialog box
add_action( 'admin_footer', 'find_posts_div', 99 );
}
/* Meta box create */
function add_custom_box_so_14416409()
{
add_meta_box(
'sectionid_so_14416409',
__( 'Select a Post' ),
'inner_custom_box_so_14416409',
'post'
);
}
/* Meta box content */
function inner_custom_box_so_14416409( $post )
{
?>
<form id="emc2pdc_form" method="post" action="">
<?php wp_nonce_field( 'find-posts', '_ajax_nonce', false); ?>
<input type="text" name="kc-find-post" id="kc-find-post" class="kc-find-post">
</form>
<?php
}
/* Ajax replacement - Verbatim copy from wp_ajax_find_posts() */
function replace_default_ajax_so_14416409()
{
global $wpdb;
// SECURITY BREACH
// check_ajax_referer( '_ajax_nonce' );
$post_types = get_post_types( array( 'public' => true ), 'objects' );
unset( $post_types['attachment'] );
$s = stripslashes( $_POST['ps'] );
$searchand = $search = '';
$args = array(
'post_type' => array_keys( $post_types ),
'post_status' => 'any',
'posts_per_page' => 50,
);
if ( '' !== $s )
$args['s'] = $s;
$posts = get_posts( $args );
if ( ! $posts )
wp_die( __('No items found.') );
$html = '<table class="widefat" cellspacing="0"><thead><tr><th class="found-radio"><br /></th><th>'.__('Title').'</th><th class="no-break">'.__('Type').'</th><th class="no-break">'.__('Date').'</th><th class="no-break">'.__('Status').'</th></tr></thead><tbody>';
foreach ( $posts as $post ) {
$title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' );
switch ( $post->post_status ) {
case 'publish' :
case 'private' :
$stat = __('Published');
break;
case 'future' :
$stat = __('Scheduled');
break;
case 'pending' :
$stat = __('Pending Review');
break;
case 'draft' :
$stat = __('Draft');
break;
}
if ( '0000-00-00 00:00:00' == $post->post_date ) {
$time = '';
} else {
/* translators: date format in table columns, see http://php.net/date */
$time = mysql2date(__('Y/m/d'), $post->post_date);
}
$html .= '<tr class="found-posts"><td class="found-radio"><input type="radio" id="found-'.$post->ID.'" name="found_post_id" value="' . esc_attr($post->ID) . '"></td>';
$html .= '<td><label for="found-'.$post->ID.'">' . esc_html( $title ) . '</label></td><td class="no-break">' . esc_html( $post_types[$post->post_type]->labels->singular_name ) . '</td><td class="no-break">'.esc_html( $time ) . '</td><td class="no-break">' . esc_html( $stat ). ' </td></tr>' . "\n\n";
}
$html .= '</tbody></table>';
$x = new WP_Ajax_Response();
$x->add( array(
'data' => $html
));
$x->send();
}
Javascript file open-posts.js
jQuery(document).ready(function($) {
// Find posts
var $findBox = $('#find-posts'),
$found = $('#find-posts-response'),
$findBoxSubmit = $('#find-posts-submit');
// Open
$('input.kc-find-post').live('dblclick', function() {
$findBox.data('kcTarget', $(this));
findPosts.open();
});
// Insert
$findBoxSubmit.click(function(e) {
e.preventDefault();
// Be nice!
if ( !$findBox.data('kcTarget') )
return;
var $selected = $found.find('input:checked');
if ( !$selected.length )
return false;
var $target = $findBox.data('kcTarget'),
current = $target.val(),
current = current === '' ? [] : current.split(','),
newID = $selected.val();
if ( $.inArray(newID, current) < 0 ) {
current.push(newID);
$target.val( current.join(',') );
}
});
// Double click on the radios
$('input[name="found_post_id"]', $findBox).live('dblclick', function() {
$findBoxSubmit.trigger('click');
});
// Close
$( '#find-posts-close' ).click(function() {
$findBox.removeData('kcTarget');
});
});

Resources