The code below is working nearly flawlessly, however my value for page title on one of my pages keeps coming up empty after a few page refreshes... It sticks for awhile, then it appears to reset to empty. I'm thinking I must have a conflict in the code below, but I can't quite figure it.
I'm allowing the user to set a custom page title for posts as well as pages via a custom "post/page title input field). Can anyone see an obvious issue here that might be resetting the page title to blank?
// ===================
// = POST OPTION BOX =
// ===================
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
//add_meta_box( $id, $title, $callback, $page, $context, $priority );
add_meta_box('post_header', 'Custom Post Header Code (optional)', 'custom_post_images', 'post', 'normal', 'low');
add_meta_box('post_title', 'Custom Post Title', 'custom_post_title', 'post', 'normal', 'high');
add_meta_box('post_title_page', 'Custom Post Title', 'custom_post_title', 'page', 'normal', 'high');
add_meta_box('postexcerpt', __('Excerpt'), 'post_excerpt_meta_box', 'page', 'normal', 'core');
add_meta_box('categorydiv', __('Page Options'), 'post_categories_meta_box', 'page', 'side', 'core');
}
}
//Adds the custom images box
function custom_post_images() {
global $post;
?>
<div class="inside">
<textarea style="height:70px; width:100%;margin-left:-5px;" name="customHeader" id="customHeader"><?php echo get_post_meta($post->ID, 'customHeader', true); ?></textarea>
<p>Enter your custom html code here for the post page header/image area. Whatever you enter here will override the default post header or image listing <b>for this post only</b>. You can enter image references like so <img src='wp-content/uploads/product1.jpg' />. To show default images, just leave this field empty</p>
</div>
<?php
}
//Adds the custom post title box
function custom_post_title() {
global $post;
?>
<div class="inside">
<p><input style="height:25px;width:100%;margin-left:-10px;" type="text" name="customTitle" id="customTitle" value="<?php echo get_post_meta($post->ID, 'customTitle', true); ?>"></p>
<p>Enter your custom post/page title here and it will be used for the html <title> for this post page and the Google link text used for this page.</p>
</div>
<?php
}
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
// called after a post or page is saved and not on autosave
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['customHeader'])
{
update_custom_meta($postID, $_POST['customHeader'], 'customHeader');
}
else
{
update_custom_meta($postID, '', 'customHeader');
}
if ($_POST['customTitle'])
{
update_custom_meta($postID, $_POST['customTitle'], 'customTitle');
}
else
{
update_custom_meta($postID, '', 'customTitle');
}
}
}
function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
}else{
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}
?>
Wordpress's auto save system may well be your problem, as I think custom fields are not passed along for auto saves (so your customHeader and customTitle post variables will be empty during an auto save).
In your save function you should check if the DOING_AUTOSAVE constant is set (this seems to be preferable to checking the post action) and return if so. Something like this:
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
See this ticket for more info: http://core.trac.wordpress.org/ticket/10744
The WordPress Codex has got an function reference for add_meta_box(), with a great example.
And yes, it uses
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
and I think you've implemented it the right way.
FYI, the solution posted here http://wordpress.org/support/topic/custom-post-type-information-disappearing worked for me and I think is much more elegant.
Related
I have two product pages of an ecommerce website: one made with Woocommerce (in WordPress) and one I coded my self in AMP.
Here is the WordPress page, and here is the AMP page. Not taking into account that the two pages are on two different subdomains, how would I redirect mobile users to the AMP version of the page ?
A similar question was asked, but it only specified how to do it for simple pages, not product pages.
Does anyone know how to that?
To answer your question, You have to hard code this following lines in your theme functions.php if you don't want to use plugin.
Following ways to make it work as per your question
Create Metabox in Product Post Type of WooCommerce
Add Input Field to the Created Metabox
Save the Input Field via save_post action hook
Input the Specific URL for each Product
Fetch the saved data from Product and redirect if it is a mobile user.
Step 1: Create Metabox
//Create Metabox
function wc_49570125_register_meta_boxes() {
add_meta_box('meta-box-id', __('Mobile Version URL', 'yourtextdomain'), 'wc_49570125_my_display_callback', 'product');
}
add_action('add_meta_boxes', 'wc_49570125_register_meta_boxes');
Step 2: Add Input Field
// Add Input Field
function wc_49570125_my_display_callback($post) {
$get_id = $post->ID;
$get_value = get_post_meta($get_id, 'wc_mobile_version_url', true);
?>
<p>
<label><?php _e('Mobile URL to Redirect', 'yourtextdomain'); ?></label>
<input type="text" name="wc_mobile_version_url" value="<?php echo $get_value; ?>"/>
</p>
<?php
}
Step 3: Save the Input Field
// save input field
function wc_49570125_save_meta_box($post_id) {
$post_type = get_post_type($post_id);
if ('product' != $post_type) {
return;
}
if (isset($_POST['wc_mobile_version_url'])) {
$mobile_version = $_POST['wc_mobile_version_url'];
update_post_meta($post_id, 'wc_mobile_version_url', $mobile_version);
}
}
add_action('save_post', 'wc_49570125_save_meta_box');
Step 4: Redirect mobile users to mobile version
// redirect input field
function wc_49570125_mobile_redirect() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if (wp_is_mobile() && $amp_location) {
wp_redirect($amp_location);
exit;
}
}
}
add_action('wp', 'wc_49570125_mobile_redirect');
Step 5: Add Discoverable Link for Google
function wc_49570125_amp_google_link() {
global $product, $post;
if (is_product()) {
$get_id = $post->ID;
$amp_location = get_post_meta($get_id, 'wc_mobile_version_url', true);
if ($amp_location) {
?>
<link rel="amphtml" href="<?php echo $amp_location; ?>"/>
<?php
}
}
}
add_action('wp_head', 'wc_49570125_amp_google_link');
I tested above code and seems it works well.
I would like to process a contact form from contact form 7 into a custom post type.
Currently, this is what I have:
<?php
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "front_post") {
//store our post vars into variables for later use
//now would be a good time to run some basic error checking/validation
//to ensure that data for these values have been set
$title = $_POST['title'];
$content = $_POST['content'];
$Interest = $_POST['Interest'];
$post_type = 'purchase';
//the array of arguements to be inserted with wp_insert_post
$new_post = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $tags,
'posted_data' => $Interest,
'post_status' => 'publish',
'post_category' => array('0',$_POST['cat']),
'post_type' => $post_type
);
//insert the the post into database by passing $new_post to wp_insert_post
//store our post ID in a variable $pid
//we now use $pid (post id) to help add out post meta data
$pid=wp_insert_post($new_post);
//we now use $pid (post id) to help add out post meta data
add_post_meta($pid, 'cust_key', $custom_field);
}
?>
Here is a link to the actual form: http://stage.icardpromotions.com/create-purchase-order/
I need to be able to pull in all of the info form this form into the custom post type "purchase"
As you can see, I am currently pulling in the post_content, post_title, etc.
I have also tried to pull in content from content form by input name "Interest" but it dose not work.
Does anyone have a clue how to do this?
function save_posted_data( $posted_data ) {
$args = array(
'post_type' => 'post',
'post_status'=>'draft',
'post_title'=>$posted_data['your-name'],
'post_content'=>$posted_data['your-message'],
);
$post_id = wp_insert_post($args);
if(!is_wp_error($post_id)){
if( isset($posted_data['your-name']) ){
update_post_meta($post_id, 'your-name', $posted_data['your-name']);
}
// if( isset($posted_data['your-email']) ){
// update_post_meta($post_id, 'your-email', $posted_data['your-email']);
// }
// if( isset($posted_data['your-subject']) ){
// update_post_meta($post_id, 'your-subject', $posted_data['your-subject']);
// }
if( isset($posted_data['your-message']) ){
update_post_meta($post_id, 'your-message', $posted_data['your-message']);
}
//and so on ...
return $posted_data;
}
}
add_filter( 'wpcf7_posted_data', 'save_posted_data' );
-------------------- Explaining It-------------------------
First make function and add a hook wpcf7_posted_data to it
---first step---
function save_posted_data( $posted_data ) {
}
add_filter( 'wpcf7_posted_data', 'save_posted_data' );
---second step---
and now u need to add some arguments to the post that needs to be populated using wp_insert_post();
$args = array(
'post_type' => 'post',
'post_status'=>'draft',
'post_title'=>$posted_data['your-name'],
'post_content'=>$posted_data['your-message'],
);
$post_id = wp_insert_post($args);
---third step---
check if that populated items is error or not
if(!is_wp_error($post_id)){ //do ur stuffs }
---fourth step---
now checking isset the field or not and updating the metas
eg post
if( isset($posted_data['your-name']) ){
update_post_meta($post_id, 'your-name', $posted_data['your-name']);
}
and in last return the value
return $posted_data;
Full code is above.
here is a quick tip as to how to go about achieving the above using your own code, first register your custom post
add_action('init', 'my_custom_post');
function (){
$args = array(
/*post type registration parameters*/
);
register_post_type( 'my_custom_post', $args );
}
next, you want to capture your posted data and create a new post
add_filter( 'wpcf7_posted_data', 'save_posted_data' );
function save_posted_data( $posted_data ) {
$args = array(
'post_type' => 'my_custom_post',
/*other default parameters you want to set*/
);
$post_id = wp_insert_post($args);
if(!is_wp_error($post_id)){
if( isset($posted_data['form-field-name']) ){
update_post_meta($post_id, 'form-field-name', $posted_data['form-field-name']);
}
//and so on ...
return $posted_data;
}
While the answer with the most upvotes in this thread works it has some flaws.
First of which is: you can still submit the form and thus create a post in wordpress if for instance you remove "disabled" tag from your submit button. So you can essentially bypass the validation.
Second problem that I had, was probably specific to my usecase, since this function triggers on any cf7 form submission on website. If you have more than one cf7 form this will create posts even if users submit something in some totally different form.
To solve the first problem I think the best way is to hook custom function to "wpcf7_before_send_mail" instead of "wpcf7_posted_data"
And to solve the second problem is to check for id of the form you wish to trigger the effect on.
This is how I solved these problems:
function save_cf7_data_to_cpt( $contact_form ) {
if( $contact_form->id() !== $my_form_id )
return; //dont run the rest if it is not the form you want it to be, $my_form_id we look up in admin or shortcode...
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$posted_data = $submission->get_posted_data();
} //we get to $post_data in this way since it is not provided like in the wpcf7_posted_data approach
$args = array(
'post_type' => 'testemonial',
'post_status'=>'draft',
'post_title'=>$posted_data['your-name'],
'post_content'=>$posted_data['your-message'],
);
$post_id = wp_insert_post($args);
if(!is_wp_error($post_id)){
if( isset($posted_data['your-name']) ){
update_post_meta($post_id, 'your-name', $posted_data['your-name']);
}
if( isset($posted_data['your-message']) ){
update_post_meta($post_id, 'your-message', $posted_data['your-message']);
}
//and so on ...
return $posted_data;
}
}
add_filter( 'wpcf7_before_send_mail', 'save_cf7_data_to_cpt' ); //hook into wpcf7_before_send_mail to ensure validation is ok
Can u also use
add_action('wpcf7_mail_sent','save_my_form_data_to_my_cpt');
add_action('wpcf7_mail_failed','save_my_form_data_to_my_cpt');
function save_my_form_data_to_my_cpt($contact_form){
$submission = WPCF7_Submission::get_instance();
if (!$submission){
return;
}
$posted_data = $submission->get_posted_data();
//The Sent Fields are now in an array
//Let's say you got 4 Fields in your Contact Form
//my-email, my-name, my-subject and my-message
//you can now access them with $posted_data['my-email']
//Do whatever you want like:
$new_post = array();
if(isset($posted_data['your-name']) && !empty($posted_data['your-name'])){
$new_post['post_title'] = $posted_data['your-name'];
} else {
$new_post['post_title'] = 'Message';
}
$new_post['post_type'] = 'inquiry'; //insert here your CPT
if(isset($posted_data['tel-901'])){
$new_post['post_content'] = $posted_data['tel-901'];
} else {
$new_post['post_content'] = 'No Message was submitted';
}
$new_post['post_status'] = 'publish';
//you can also build your post_content from all of the fields of the form, or you can save them into some meta fields
if(isset($posted_data['your-email']) && !empty($posted_data['your-email'])){
$new_post['meta_input']['sender_email_address'] = $posted_data['your-email'];
}
if(isset($posted_data['checkbox-674']) && !empty($posted_data['checkbox-674'])){
//$new_post['meta_input']['sender_name'] = $posted_data['checkbox-674'];
$ChildSeat=$posted_data['checkbox-674'];
$Child_Seat='';
for($a=0;$a<count($ChildSeat);$a++)
{
$data['checkbox-674']=$_POST['checkbox-674'][$a];
$Child_Seat.=$data['checkbox-674'].'<br>';
$new_post['post_content'] = $Child_Seat;
}
}
//When everything is prepared, insert the post into your Wordpress Database
if($post_id = wp_insert_post($new_post)){
//Everything worked, you can stop here or do whatever
} else {
//The post was not inserted correctly, do something (or don't ;) )
}
return;
}
there is a plugin to do this, Post My CF7 Form.
The plugin allows you to map a CF7 form and its fields to a an existing post type or a new custom post type.
The mapping process is done using an interactive UI admin page which gives you the option to map your fields to post fields (title, content, excerpt, slug, author) as well as post meta-fields.
In addition, the plugin also introduces a save submit button to allow users to save a draft version of the form, this is especially useful for large complex forms.
The plugin can automatically load taxonomy terms in select/checkbox/radio fields that have been mapped to that taxonomy, thus enabling created posts to be automatically assigned to users selected terms.
The plugin has multiple hooks & filters to customise the process flow.
My question is on save($postID) function. Here there is a parameter $postID which is using in the function for saving as id. I see that this $postID has a null value. How does actual post id work for $postID?
This is the simple meta-box code
/* simple meta box */
/* creating field */
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
function testfield(){
global $post;
?>
<input type="text" name="Asif" id="Asif" value="<?php echo get_post_meta($post->ID, 'Sumon', true); ?>">
<?php
}
/* end of creating field */
/* storing field after pressing save button */
add_action('save_post', 'save');
function save($postID){
if (!defined('DOING_AUTOSAVE') && !DOING_AUTOSAVE) {
return $postID;
}
else
{
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['Asif'])
{
update_custom_meta($postID, $_POST['Asif'], 'Sumon');
}
}
}
// saving in postmeta table
function update_custom_meta($postID, $newvalue, $field_name){
if(!get_post_meta($postID, $field_name)){
// create field
add_post_meta($postID, $field_name, $newvalue);
}
else{
//update field
update_post_meta($postID, $field_name, $newvalue);
}
}
You've used the wrong Action Hook.
Instead of using add_action('admin_menu', 'my_post_options_box');
Use add_action('add_meta_boxes', 'my_post_options_box');
add_action('add_meta_boxes', 'my_post_options_box');
function my_post_options_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box('post_header', 'Asif, save me!', 'testfield', 'post', 'normal', 'low');
}
}
You can look in to http://codex.wordpress.org/Function_Reference/add_meta_box for detailed overview.
Some SO Question/Answers you can look into.
Add multiple dates to custom post type in Wordpress
how to add a meta box to wordpress pages
While Saving Post
Action save_post automatically passes Post ID to callback function. Which you can use inside your callback function.
Some already answered quesitons
https://wordpress.stackexchange.com/questions/41912/perform-an-action-when-post-is-updated-published
Reference
http://codex.wordpress.org/Plugin_API/Action_Reference/save_post
I'm trying to modify Wordpress "press this" http://codex.wordpress.org/Press_This to post with the post type that my theme created.
By default Post this open the link http://www.xxxx.com/wp-admin/post-new.php
And I want it to open http://www.xxxx.com/wp-admin/post-new.php?post_type=recipe
Have tried the following code in Functions.php but nothing happens
function press_this_ptype($link) {
$post_type = 'recipe';
$link = str_replace('post-new.php', "post-new.php?post_type=$post_type", $link);
return $link;
}
add_filter('shortcut_link', 'press_this_ptype', 11);
Studying the file, I think the best entry point is the function wp_update_post() that has a filter we can use:
add_action( 'load-press-this.php', function() # Add filter only in Press This
{
add_filter( 'wp_insert_post_data', function( $data, $postarr )
{
$data['post_type'] = 'portfolio'; # <-- adjust CPT
return $data;
}, 10, 2 );
});
After that, we'll notice the need to hide some stuff from the Press This screen (post formats, categories, tags):
add_action( 'admin_head-press-this.php', function()
{
?>
<style type='text/css'>
#categorydiv, #tagsdiv-post_tag, /* Category and tag meta boxes */
#submitdiv div.inside p:nth-of-type(2) /* Post formats */
{
display:none;
}
</style>
<?php
});
I'm trying to use custom meta boxes in wordpress. My goal at the moment is to create a meta box with a checkbox that I can use as a switch to turn on certain content. I've been scouring the web trying to piece together something that works, and so far I've gotten far enough to where I can generate a meta box with a checkbox, but the checked value isn't carrying over to the loop for some reason. When I try to output the array to see if I can get anything out of it, it's empty. I've looked at a ton of things and tried several meta box creation scripts, but I can't get any of them to work. This method looked to be the most promising, but now I'm stuck. Is there something important I'm missing here? It's as if the data isn't being saved. Code included below:
Meta Box functions. Located in functions.php:
// Checkbox Meta
add_action("admin_init", "checkbox_init");
function checkbox_init(){
add_meta_box("checkbox", "Checkbox", "checkbox", "post", "normal", "high");
}
function checkbox(){
global $post;
$custom = get_post_custom($post->ID);
$field_id = $custom["field_id"][0];
echo '<label>Check for yes</label>';
$field_id_value = get_post_meta($post->ID, 'field_id', true);
if($field_id_value == "yes") {
$field_id_checked = 'checked="checked"';
}
echo ' <input type="checkbox" name="field_id" value="yes" '.$field_id_checked.' />';
}
// Save Meta Details
add_action('save_post', 'save_details');
function save_details(){
global $post;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post->ID;
}
update_post_meta($post->ID, "field_id", $_POST["field_id"]);
}
Code used to output content when checkbox is checked. This is also located in functions.php. The function is used in the loop.
function custom_content() {
if(isset($_POST['field_id']) && $_POST['field_id'] == 'yes') {
echo "It works!";
}
}
change your function on functions.php to
function custom_content($id) {
$field_id = get_post_meta($id, 'field_id', true);
if($field_id == yes) {
echo "It works!";
}
else{
echo 'Not working...';
}
}
And your template, call it inside the loop like the ff:
custom_content(get_the_ID());