How add custom data in post page? Wordpress - wordpress

<form method="post">
<input type="text" name="title" /> //Title
<input type="text" name="desc" /> //Description
<input type="text" name="age" /> //Age autor
</form>
This code add title and description in new article. But how do I add custom date? ex. age input.
$title = $_POST['title'];
$desc = $_POST['desc'];
$date = array(
'post_title' => $title,
'post_content' => $desc,
'post_status' => 'publish'
);
wp_insert_post($date);

look into custom meta boxes. Here is an excellent article about it http://wp.smashingmagazine.com/2011/10/04/create-custom-post-meta-boxes-wordpress/
The initial function that allows you to save custom fields is add_post_meta(). Example:
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
You could do the following if custom meta boxes is not what you are looking for:
$post_ID = wp_insert_post($date);
add_post_meta( $post_ID, 'custom_field', 'content for custom field', true );

wp_insert_post will return an ID. You would then use that to add post meta.
https://codex.wordpress.org/Function_Reference/wp_insert_post
https://codex.wordpress.org/Function_Reference/add_post_meta
E.g.
$id = wp_insert_post( $date );
$age = {GET AND SANITIZE YOUR AGE INPUT}
add_post_meta( $id, 'age', $age, true );

Related

Create WordPress post from frontend featured image and ACF

I am running this function:
function create_post() {
ob_start();
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$post_category = $_POST['cat'];
$post_content = $_POST['post_content'];
$new_post = array(
'ID' => '',
'post_author' => $user->ID,
'post_category' => array($post_category),
'post_content' => $post_content,
'post_title' => $post_title,
'post_status' => 'publish'
);
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect($post->guid);
}
?>
<form method="post" action="">
<input type="text" name="post_title" size="45" id="input-title" placeholder="Voer hier de titel van het nieuwsbericht in"/>
<?php wp_dropdown_categories('orderby=name&hide_empty=0&exclude=1&hierarchical=1'); ?>
<textarea rows="5" name="post_content" cols="66" id="text-desc" placeholder="Voer hier de tekst van het bericht in"></textarea>
<p>
Kies hieronder de afbeelding van het nieuwsbericht.
</p>
<input type="file" id="featured_image" name="featured_image" accept="image/*">
<br/><br/>
<input type="hidden" name="new_post" value="1"/>
<input class="subput round" type="submit" name="submit" value="Nieuwsbericht aanmaken"/>
</form>
<?php
return ob_get_clean();
}
add_shortcode('create_post', 'create_post');
It creates a post on submit but how do I add the image chosen in the input type="file" as featured image?
Also I want to fill ACF fields with this frontend form.
I think you're looking for set_post_thumbnail(). There's a good tutorial here that you could base your code on.
Excerpt with relevant code:
<?PHP
//prepare upload image to WordPress Media Library
$upload = wp_upload_bits( $IMGFileName, null, file_get_contents( $IMGFilePath, FILE_USE_INCLUDE_PATH ) );
// check and return file type
$imageFile = $upload['file'];
$wpFileType = wp_check_filetype( $imageFile, null );
// Attachment attributes for file
$attachment = array(
'post_mime_type' => $wpFileType['type'], // file type
'post_title' => sanitize_file_name( $imageFile ), // sanitize and use image name as file name
'post_content' => '', // could use the image description here as the content
'post_status' => 'inherit'
);
// insert and return attachment id
$attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId );
// insert and return attachment metadata
$attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile );
// update and return attachment metadata
wp_update_attachment_metadata( $attachmentId, $attachmentData );
// finally, associate attachment id to post id
$success = set_post_thumbnail( $postId, $attachmentId );
// was featured image associated with post?
if ( $success ) {
$message = $IMGFileName . ' has been added as featured image to post.';
} else {
$message = $IMGFileName . ' has NOT been added as featured image to post.';
}
?>

Can I set registered Custom Taxonomy For my Custom Post Type in code?

I registered Custom Taxonomy through Custom Post Type UI Plugin and assigned them for my CPT Advertisements.
When I add new Advertisement through function() after submit my form, I know set all I need (title, custom_fields...) but can I set already defined some of custom taxonomies for my new Post? I know to do that in wp-admin ... but I had to set it in code, when I choose one of the custom taxonomies from the selectbox...
Custom taxonomies assigned to my Custom Post Type:
Set Custom taxonomy through selectbox:
<select name="taxonomy-market-type" class="custom-select" id="taxonomy-category">
<?php
$terms = get_terms( array(
'taxonomy' => 'advertisement_category',
'hide_empty' => false) );
?>
<option value="" hidden>Choose category</option>
<?php foreach ($terms as $term) { ?>
<option value="<?php echo $term->slug ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select>
Function, where I add New Custom Post Type:
function addAdvertisement() {
header('Content-Type: application/html;charset=utf-8');
$uploadDir = wp_upload_dir();
// Create post object
$my_post = array(
'post_title' => $_POST['name'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'advertisements'
);
$post_id = wp_insert_post( $my_post);
if(isset($POST['category'])) {
// add custom taxonomy here
}
// Insert the post into the database
add_post_meta($post_id, 'nazov_inzeratu', $_POST['name']);
add_post_meta($post_id, 'popis_inzeratu', $_POST['description']);
add_post_meta($post_id, 'fotka', implode(',', $uploadedImages));
add_post_meta($post_id, 'id_inzerat', $post_id);
echo get_permalink($post_id);
wp_die();
}
Is that even possible, please? Thanks for the advices
Yes, it is possible to assign custom taxonomies to custom post types by calling wp_set_post_terms() as follows.
if(isset($POST['category'])) {
$adv_cat = array($POST['category']);
wp_set_post_terms( $post_id, $adv_cat, 'advertisement_category');
}
I hope this will work.
Please have a look at this codex page for further info.

Wordpress widget: Checkbox not saving state

I have a Wordpress widget with checkboxs. I am trying to set the default state to "checked" for one of the checkboxes by setting a variable in my defaults array to true. If I uncheck the box and try to save the widget the checkbox reverts back to being checked, so basically I can't uncheck the box.
I have other checkboxs with the same configuration and they are working correctly. Does anyone see anything wrong with my code below?
$defaults = array(
'widget' => 'cat',
'type' => 'list',
'selected' => 0,
'use_products' => 'true',
'title' => '',
'sub_title' => '',
'operator' => 'IN',
'print_before_widget' => 'true',
'print_after_widget' => 'true',
'hide_empty' => 'true',
'hide_on_cats' => 'false',
'custom_class' => ''
);
$instance = parse_args( $instance, $defaults );
extract( $instance );
<p>
<input class="checkbox"
<?php if ( isset( $use_products ) && $use_products=='true' ) { echo 'checked="checked"'; } ?>
id = "<?php echo $this->get_field_id( 'use_products' ); ?>"
name = "<?php echo $this->get_field_name( 'use_products' ); ?>"
value = "true"
type = "checkbox"
/>
<label for="<?php echo $this->get_field_id( 'use_products' ); ?>" ><?php _e( 'Show Product Categories', textdomain ); ?></label>
</p>
There may be several things wrong here but you may not be giving enough context.
I am assuming this is a snippet from inside the form() method of your widget. The form() method is passed the $instance variable, which contains the current values of all the widget settings. You dont appear to be using that at all. Your value for the checkbox is hardcoded as true, and your $defaults array isnt merged or overridden by anything - your just setting defaults and using them directly - your not using values from the database.
https://codex.wordpress.org/Widgets_API#Default_Usage
Edit
In your update method, for the checkbox, you should do something like the following...
public function update($new_instance, $old_instance){
$instance = array();
$instance['checkbox_key'] = ( ! empty( $new_instance['checkbox_key'] ) ) ? strip_tags( $new_instance['checkbox_key'] ) : '';
return $instance;
}
If this doesnt make sense in your context, you should update your answer to include the update() method.

wp_insert_post not adding category

I'm building a WordPress theme where people can submit posts using wp_insert_post. The code below adds the post title but does not add the category specified by the user. Instead it puts it in uncategorized.
How do I get it to add the new category to the post when submitted?
if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$new_cat_ID = $_POST['category'];
//Checking if category already there
$cat_ID = get_cat_ID( $_POST['newcat'] );
//If not create new category
if($cat_ID == 0) {
$cat_name = array('cat_name' => $_POST['newcat']);
wp_insert_category($cat_name);
}
//Get ID of newly created category
$new_cat_ID = get_cat_ID($_POST['newcat']);
// Create post object
$new_post = array(
'ID' => '',
'post_title' => $post_title,
'post_status' => 'publish',
'post_author' => $user->ID,
'tax_input' => array( 'category' => $new_cat_ID )
);
// Insert the post into the database
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( home_url() );
exit;
}
Here's the HTML for the form:
<form style="" action="" method="post" id="foo">
<input type="hidden" name="new_post" value="1"/>
<input type="text" name="post_title" value="title" id="input-title"/>
<input type="text" name="category" value="apples" id="category" />
<input type="submit" value="Login">
</form>
The category input should be:
<input type="text" name="newcategory" value="apples" id="category" />
In my tests, wp_insert_category did not work and wp_insert_term had to be used (as per this forum thread).
Your wp_redirect is not taking where you thing it does. The section //This will redirect you to the newly created post is plain wrong.
The following is a working example with a security layer added with wp_nonce_field, but you must add User Input Data Validation.
Also, I'm testing while logged in, so it works. Your code does not take care of $user->ID, research for get_current_user to get this right.
<?php
if ( isset( $_POST['noncename_so_17539370'] ) && wp_verify_nonce( $_POST['noncename_so_17539370'], 'nonce_so_17539370' ) )
{
if( isset($_POST['new_post']) == '1' ) {
//Checking if category already there
$cat_ID = get_cat_ID( $_POST['newcat'] );
//If not create new category
if( !$cat_ID ) {
$arg = array( 'description' => "my description", 'parent' => 0 );
$cat_ID = wp_insert_term($_POST['newcat'], "category", $arg);
}
// Create post object
$new_post = array(
'ID' => '',
'post_title' => $_POST['post_title'],
'post_status' => 'publish',
//'post_author' => $user->ID,
'tax_input' => array( 'category' => $cat_ID )
);
// Insert the post into the database
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post
$post = ;
wp_redirect( get_permalink( $post_id ) );
exit;
}
} else {
echo 'ERROR';
}
?>
<form style="" action="" method="post" id="foo">
<?php wp_nonce_field( 'nonce_so_17539370', 'noncename_so_17539370' ); ?>
<input type="hidden" name="new_post" value="1"/>
<input type="text" name="post_title" value="title" id="input-title"/>
<input type="text" name="newcat" value="apples" id="category" />
<input type="submit" value="Login">
</form>

wp_query not filtering tax_query correctly in pre_get_posts

I'm having a problem with the following situation: I am creating a custom form for searching my custom post type (immobiliare) and attached to this I have 2 custom taxonomies: location and tipologia.
My searchform.php is:
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
<input type="hidden" value="proceed" name="s" id="s" />
<fieldset>
<legend>Ricerca per:</legend>
<label class="screen-reader-text" for="query">Testo:</label>
<input type="text" value="<?php the_search_query(); ?>" name="query" id="query" />
</fieldset>
<fieldset>
<label class="screen-reader-text" for="s">Tipologia:</label>
<?php wp_dropdown_categories(array(
'hide_empty' => 0,
'taxonomy' => 'tipologia',
'name' => 'tipologia',
'show_option_all' => 'Nessuna Preferenza'
)); ?>
</fieldset>
<fieldset>
<label class="screen-reader-text" for="s">Località:</label>
<?php wp_dropdown_categories(array(
'hide_empty' => 0,
'taxonomy' => 'location',
'name' => 'location',
'show_option_all' => 'Nessuna Preferenza'
)); ?>
</fieldset>
<input type="submit" id="searchsubmit" value="Search" />
</form>
As you can see, I have 3 fields: 1 is a textfield and the other 2 are dropdowns with my taxonomies. I want the user to be able to search for these fields. I had to hack the "s" input type because it would not let me submit empty queries and added a "query" field instead.
My functions.php file is as follows:
<?php
// Start LOGGING
if(!function_exists('_log')){
function _log( $message ) {
if( WP_DEBUG === true ){
if( is_array( $message ) || is_object( $message ) ){
error_log( print_r( $message, true ) );
} else {
error_log( $message );
}
}
}
}
// end LOGGING
// start SEARCH FORM
function ij_get_int($var){
if (isset($var)) {
$int_var = intval($var);
if ($int_var > 0)
return $int_var;
}
return false;
}
function ij_get_str($var) {
$str_var = esc_attr($var);
if (strlen($str_var) > 0)
return $str_var;
return false;
}
function custom_search_results($query) {
if ($query->is_search && $query->is_main_query()) {
$tax_query = array(
'relation' => 'AND',
);
$location = ij_get_int($_GET['location']);
$tipologia = ij_get_int($_GET['tipologia']);
if ($location) {
array_push($tax_query, array(
'taxonomy' => 'location',
'field' => 'id',
'terms' => $location,
'operator' => 'IN'
));
}
if ($tipologia) {
array_push($tax_query, array(
'taxonomy' => 'tipologia',
'field' => 'id',
'terms' => $tipologia,
'operator' => 'IN'
));
}
$query->set('tax_query', $tax_query);
$query->set('s', ij_get_str($_GET['query']));
$query->set('post_type', 'immobiliare');
}
}
add_action('pre_get_posts', 'custom_search_results');
// end SEARCH FORM
?>
Here I hook into the response of my custom form and add:
The actual query ("query" and not "s"), when the user inputs valid data.
The filter by taxonomy, when needed.
I have no clue why this is not working out (spent a day!), I can see my query coming back with the correct 's' parameter:
$query->set('s', ij_get_str($_GET['query']));
but not the taxonomy filter.
What am I doing wrong? I want to use the standard Loop in my search.php file, so in some way I want my hook function to get automatically plugged into the loop. One curious thing is that if I create a new WP_Query object with the same setup (and not use the "set" method) it returns exactly what I want! I tried doing $query = new WP_Query... but this is not working too!!
If I dump the query request on the top of my search.php I get the following:
SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND 0 = 1 AND (((wp_posts.post_title LIKE '%vil%') OR (wp_posts.post_content LIKE '%vil%'))) AND wp_posts.post_type = 'immobiliare' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
Does anyone have any hints to share? You would be really cool to give me a hand!
Thanks
Dan
You probably solved this by now, but your query has ... where 1=1 and 0=1 ... so it wouldn't return anything since you are asking for a record set of items both true and false.

Resources