Adding custom taxonomy terms to WP from a front end form - php

I'm trying to add terms to my custom taxonomy from a front-end form. I managed to create the form populate the select by values from another custom post type's posts. But I think that my form handler is not working... When I hit submit the form just takes me to "http://therealaddress.com/wp-admin/admin-post.php" and nothing happens (no new term to the taxonomy, no forwarding to the page I want)... (and yes, I changed therealaddress.com to hide my real address, it's not the wrong address :D)
I would like to forward the user back to the page where the form is after the submission.
My form handling part looks like this in my themes funtions.php
function horse_taxonomy_adder() {
// splitting the select options value from "horses-real-name:Horses Real Name" to "horses-real-name" and "Horses Real Name"
$horsename = ( $_POST['horsename'] );
$hn_slug = split(':', $horsename)[0];
$hn_name = split(':', $horsename)[1];
wp_insert_term(
'hn_name', // the term
'hevoset', // the taxonomy
array(
'slug' => $hn_slug,
)
);
// add the admin notice
$admin_notice = "success";
// redirect the user to the page called "Hallinta"
$page = get_page_by_title('hallinta');
$this->wp_redirect(get_permalink($page->ID));
exit;
}
add_action('admin_post_add_horsetaxonomy','horse_taxonomy_adder');
My form looks like this:
<form action="http://therealaddress.com/wp-admin/admin-post.php" method="POST">
<input type="hidden" name="action" value="horse_taxonomy_adder">
<div class="form-group">
<label for="exampleInputEmail1">Valitse hevonen jolle päiväkirja luodaan</label>
<select name="horsename">
<?php
global $post;
$args = array( 'numberposts' => -1, 'post_type' => 'hevonen');
$posts = get_posts($args);
foreach( $posts as $post ) : setup_postdata($post); ?>
<option value="<? echo $post->post_name; ?>:<?php the_title(); ?>"><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" name="submit" class="btn btn-primary">Lisää päiväkirja</button>
</form>

Related

How to change the posts category with a button click

I am trying to create a button "Approved" to change the post category from it's current one to the "approved" category. I don't mind if it reloads the page or not. I would also like to redirect the page afterward to the next post in the original category.
I have found some questions on this already but am ultimately lost on how to get this all together and working.
<?php add_shortcode('approved_button', 'brist_approved_button_function');
function brist_approved_button_function() {
ob_start(); ?>
<form method="post" action="approved.php">
<input type="submit" value="Approved" name="submit"> <!-- assign a name for the button -->
</form>
<?php
wp_set_object_terms( $post_id, intval( $_POST['approved'] ), 'category', false );
$output = ob_get_clean();
return $output;
}?>
I figured it out. Though it was a head-scratcher for me. If anyone else if having the same issue, note the code below. You have to create the select and then have the 'selected' option on the category you want the post to change to. Then, in the CSS, hide the select input, only leaving the button.
<?php add_shortcode('approved_button', 'approved_button_function');?>
<?php function approved_button_function() { ob_start();?>
<div class="approval">
<form action="" id="update-post" method="post">
<?php wp_dropdown_categories( "selected='categoryId'&exclude=21&class=approval-select&show_count=1&hierarchical=1&orderby=name&order=ASC&&hide_empty=0&show_option_all=Choose An Option" ); ?>
<input class="approval-button" type="submit" name="submit" value="Approve" />
</form>
</div>
<?php if ( array_key_exists('cat', $_POST )) {
global $post;
$post_id = $post->ID;
wp_set_object_terms( $post_id, intval( $_POST['cat'] ), 'category', false );
} ?>

Accessing variable from within a function, outside of the function php / wordpress

I've created a variable within a function it looks like this:
function my_plugin_options() {
//must check that the user has the required capability
if (!current_user_can('manage_options'))
{
wp_die( __('You do not have sufficient permissions to access this page.') );
}
// variables for the field and option names
$opt_name = 'mt_favorite_color';
$hidden_field_name = 'mt_submit_hidden';
$data_field_name = 'mt_favorite_color';
// Read in existing option value from database
$opt_val = get_option( $opt_name );
doingthistest($opt_val);
// See if the user has posted us some information
// If they did, this hidden field will be set to 'Y'
if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == 'Y' ) {
// Read their posted value
$opt_val = $_POST[ $data_field_name ];
// Save the posted value in the database
update_option( $opt_name, $opt_val );
// Put a "settings saved" message on the screen
?>
<div class="updated"><p><strong><?php _e('settings saved.', 'help-menu-settings' ); ?></strong></p></div>
<?php
}
// Now display the settings editing screen
echo '<div class="wrap">';
// header
echo "<h2>" . __( 'Help block details', 'help-menu-settings' ) . "</h2>";
// settings form
?>
<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">
<p><?php _e("Whatever:", 'menu-test' ); ?>
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
</p><hr />
<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>
</form>
<span><?php echo $opt_val ?></span>
</div>
<?php
}
Now I can echo out the $opt_val variable within the scope of that function but i'm struggling to access it outside.
You'll see where I set the variable $opt_val = get_option( $opt_name ); below it I pass it to a function doingthistest($opt_val); then I create an action below so I can call it in another page (WordPress method).
So my action below looks like:
add_action('testingthis', 'doingthistest');
function doingthistest(t) {
var_dump(t);
}
for some reason, the variable isn't getting passed to my action. Am I misunderstanding something?
I call it in another page like this:
<span>info is there: <?php do_action( 'testingthis' ) ?></span>
if you want something to be available in a different page (therefore presumably during a different HTTP request?) then you'd have to put it into a session variable or other persistent storage (e.g. file, database) and the retrieve it from there in your other page. HTTP is inherently stateless and the server won't remember the value of your variables from one request to the next unless you use one of the above mechanisms to store them.
Calling doingthistest($opt_val); within the context of the code you posted will dump the variable onto that page. But then if you call that same method from another page entirely - which must by definition be in a different request - it doesn't automatically remember what you the value of it was last time. It's a separate request with a separate context.
I don't understand the Wordpress stuff precisely, but I suspect your action would be better looking something like this:
add_action('testingthis', 'doingthistest');
function dosomething($o) {
var_dump(get_option( $opt_name ));
}
But obviously you'd have to set the value of $opt_name somehow. In your sample code it's hard-coded but I don't know if that's really how you're setting it in the finished solution.

Updating different forms at the same time

Current Situation
So, this is a follow up question from my previous question (Submit button to affect multiple files)
The approach was good in terms of how to "click" multiple buttons together by using a "super-button" (patent pending) by #oMiKeY. It does what it is supposed to do, clicking all buttons.
The mark up is the following:
Title.php
<form role="form" method="post">
<div class="edit_title">
<input type="hidden" value="<?php echo $post_id; ?>">
<?php post_input_box( $post_id, 'post_title', array( 'placeholder' => 'Article title..', 'value' => $post->post_title ) ); ?>
<div class="update-button-wrap">
<input id="save_button" type="submit" name="update_product" value="<?php esc_attr_e( 'Update', 'site' ); ?>"/>
</div>
</div>
</form>
Content.php
<form role="form" method="post">
<div class="edit_content">
<?php post_input_box( $post_id, 'post_content', array( 'placeholder' => 'Short description..', 'value' => $post->post_content ), 'textarea' ); ?>
</div>
<div class="update-button-wrap">
<input id="save_button" type="submit" name="update_product" value="<?php esc_attr_e( 'Update', 'site' ); ?>"/>
</div>
</form>
Article.php
<button type='button' onclick="$('[type="submit"]').click()">Submit</button>
Problem
So, when the "Submit" button is clicked, both buttons in each title.php and content.php are also clicked (ie. in regards to clicking buttons, it works fine). However, because two forms are simultaneously clicked, only the second one is updated (either content or title) while the first one is ignored, when both data are needed to be updated.
My approach
Now, I can merge two files together and have both title and content within a single form, but that really messes up my overall setup and I heard it is better to have multiple smaller php files for updating and speed than a large one big file.
Or here is my another approach.
In the article.php, I will have the form and submit button while the title.php and content.php only has the editable forms. Then these two forms are somehow linked to the form in article.php, like the image below.
Do you think the second approach can be achieved or any other suggestions?
Thanks
Just add a global form on article.php and drop the title and content forms (and submit buttons). Every named input inside the global form will be submitted together no matter what php file generated them.
Edit:
Title.php
<div class="edit_title">
<input type="hidden" value="<?php echo $post_id; ?>">
<?php post_input_box( $post_id, 'post_title', array( 'placeholder' => 'Article title..', 'value' => $post->post_title ) ); ?>
</div>
Content.php
<div class="edit_content">
<?php post_input_box( $post_id, 'post_content', array( 'placeholder' => 'Short description..', 'value' => $post->post_content ), 'textarea' ); ?>
</div>
Article.php
<form role="form" method="post">
<?php include "Title.php"; include "Content.php"; ?>
<button type='submit'>Submit</button>
</form>
Option 2:
Alternatively you could use some sort of functionality that allows you to create forms only once, even if you have "inner forms". This way Title.php and Content.php would also work as standalone code snippets.
$formDeep = 0;
function openForm() {
global $formDeep;
if ($formDeep == 0) {
echo "<form role=\"form\" method=\"post\">";
}
$formDeep++;
}
function closeForm() {
global $formDeep;
$formDeep--;
if ($formDeep == 0) {
echo "</form>";
}
}
Title.php
<?php openForm(); ?>
<div class="edit_title">
<input type="hidden" value="<?php echo $post_id; ?>">
<?php post_input_box( $post_id, 'post_title', array( 'placeholder' => 'Article title..', 'value' => $post->post_title ) ); ?>
</div>
<?php closeForm(); ?>
Content.php
<?php openForm(); ?>
<div class="edit_content">
<?php post_input_box( $post_id, 'post_content', array( 'placeholder' => 'Short description..', 'value' => $post->post_content ), 'textarea' ); ?>
</div>
<?php closeForm(); ?>
Article.php
<?php openForm(); ?>
<?php include "Title.php"; include "Content.php"; ?>
<button type='submit'>Submit</button>
<?php closeForm(); ?>

ACF update_field associated with a User

I've created some custom fields on the user profile page in WordPress.
I've managed to build a front end editor for the user to change some e-mail preferences:
<?php if( isset($_POST['preferences']) ) :
update_field('planner-reminders', $_POST['planner-reminders'], 'user_'.$user_id.'');
update_field('event-suggestions', $_POST['event-suggestions'], 'user_'.$user_id.'');
update_field('woa-updates', $_POST['woa-updates'], 'user_'.$user_id.'');
echo '<p class="success">E-Mail Prefereneces Updated<p>';
endif; ?>
<form action="<?php the_permalink(); ?>" method="POST" class="user-email-settings">
<!-- planner reminders -->
<?php
$field = get_field('planner-reminders', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="planner-reminders" name="planner-reminders" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="planner-reminders">I don't want to revieve reminders about events I've added to my planner.</label>
<?php $checked = false; ?>
<!-- event suggestions from WOA -->
<?php
$field = get_field('event-suggestions', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="event-suggestions" name="event-suggestions" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="event-suggestions">I don't want to recieve suggestions about events I may be interested in.</label>
<?php $checked = false; ?>
<!-- updates from WOA -->
<?php
$field = get_field('woa-updates', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="woa-updates" name="woa-updates" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="woa-updates">I don't want to recieve e-mail updates from What's On Advisor.</label>
<?php $checked = false; ?>
<input type="submit" value="Save Preferences" name="preferences" id="preferences" />
</form>
Now, this actually seems to work. If I update a checkbox it shows and checked/unchecked as it should, and it shows correctly in the front end and the back end.
But, when I try to query this setting with a wp_query to actually send the e-mails to those who haven't opted out, it bug out a little.
If the user opts out, then opts back in, the wp_query doens't pick them up. It only picks them up when I go into the wp-admin area and update their user profile. I don't actually have to change anything, just open the user up and click update.
Here's the wp_query just incase:
<?php $args = array(
'role' => 'Subscriber',
'meta_key' => 'planner-reminders',
'meta_value' => '0',
'meta_compare' => '=='
); ?>
<?php $user_query = new WP_User_Query( $args ); ?>
<?php if ( ! empty( $user_query->results ) ) : ?>
etc. etc.
Any ideas how I can get this working properly? Is there a function to fake a click on the 'Update User' button in wp-admin?
Thanks.
When the user opts out, the $field value will be empty, and therefore the value-attribute of the checkboxes will be empty. I haven't fully tested it, but this can yield unexpected behaviour in your setup. When a form with an unchecked checkbox is submitted through a POST request, the checkbox name will not be set in the $_POST array, which is why you should, in this case, set the value-attribute of the checkboxes to "1", so it is properly stored via update_field.
Could you try changing the checkbox values in the code posted above to "1" for the checkbox input elements? That would be value="1" instead of value="<?php echo $field; ?>".
To prevent PHP notices being generated for inexistent array keys, I would advise to change
update_field('planner-reminders', $_POST['planner-reminders'], 'user_'.$user_id.'');
to
update_field('planner-reminders', empty( $_POST['planner-reminders'] ) ? '0' : '1', 'user_'.$user_id.'');
as well.

Print Form Data Into Array As 'value"

Learning my first php search form, be gentle!
I'm looking to fill the 'value' with the number input on the search form. Everything I have tried either breaks the page or has no effect.
I'm trying to input my $input_price into the value part of my argument.
Here is my search form
<form method="post" action="http://mysite/searchresults">
<fieldset>
<!-- TEXT INPUT SELECTION -->
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<!-- END TEXT INPUT SELECTION -->
<input type="text" name="input_price"/>
<input type="submit" id="searchsubmit" value="Search" />
</fieldset>
</form>
And here is the receiving page
<?php
$args['meta_query'][] = array(
'key' => 'price',
'value' => '($input_price)',
'type' => 'numeric',
'compare' => '<=',
'order' => 'DSC'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h1><?php the_title() ;?></h1>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p>Sorry, there are no posts to display</p>
<?php endif; ?>
Thanks!
Firstly, your data is being sent to the receiving script via the POST HTTP method, so you can access those variables with PHP's $_POST superglobal using the element's name attribute as the key:
$input_price = $_POST['input_price'];
Next, the brackets around $input_price should not be used here. Finally, single quotes do not parse variables inside them, as in this example:
'value' => '($input_price)',
But double quotes will, or simply not using quotes at all:
'value' => "$input_price",
'value' => $input_price,

Categories