WordPress.org

Ready to get started?Download WordPress

Forums

Post version issues (16 posts)

  1. pszeinert
    Member
    Posted 3 years ago #

    I have posted quite a few times trying to resolve some problems related to saving custom posts and setting the $post_title automatically. I finally found a method that works rather well, but now I am having some issues with the publish and update processes.

    The current code is as follows:

    if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && ($_POST['post_type'] == "sport_event")) {
    
    		global $post;
    
    		if(isset($post->ID)) {
    			$title_ID = $post->ID;
    		} else {
    			unset($title_ID);
    		}
    
    		$event_team = $_POST["event_team"];
    		$event_opponent = $_POST["event_opponent"];
    		$event_date = $_POST["event_date"];
    
    		$my_post_title = ($event_team ." vs. " .$event_opponent ." - " .$event_date);
    		$my_post_name = sanitize_title($event_team ."-vs-" .$event_opponent ."-" .$event_date);
    
    		// Add the content of the form to $post as an array
    		$custom_title = array(
    				'ID' => $title_ID, //Are you updating an existing post?
    				'post_content' => 'This is a custom post of the sport_event type. If you can see this text, something is wrong', //The full text of the post.
    				'post_name' => $my_post_name, // The name (slug) for your postet the status of the new post.
    				'post_title' => $my_post_title,
    				'post_type' => 'sport_event',
    				'post_status' => 'future',
    				'post_author' => 1
    			); 
    
    		$title_meta_ID = wp_insert_post ($custom_title);
    
    		add_post_meta($title_meta_ID, "event_team", $_POST["event_team"]);
    		add_post_meta($title_meta_ID, "event_opponent", $_POST["event_opponent"]);
    		add_post_meta($title_meta_ID, "event_date", $_POST["event_date"]);
    		add_post_meta($title_meta_ID, "event_time", $_POST["event_time"]);
    		add_post_meta($title_meta_ID, "territory", $_POST["territory"]);
    		add_post_meta($title_meta_ID, "region", $_POST["region"]);
    		add_post_meta($title_meta_ID, "game_audio", $_POST["game_audio"]);
    		add_post_meta($title_meta_ID, "local_score", $_POST["local_score"]);
    		add_post_meta($title_meta_ID, "opponent_score", $_POST["opponent_score"]);
    
    	}

    There is probably some optimization that could take place, but for the moment, my concern is that when I first publish it creates two entries. One is an Auto Draft with no information, and the other is the correct post with all desired fields set.

    I am fairly certain I am not handling the post_ID correctly because if I edit a post and click update, it creates yet another Auto Draft and a new post with all the updated information. The total post count after an publish and update routine is now four.

    In case it helps, here is some of the code related to the custom post:

    add_action('init', 'sport_event_register');
    
    function sport_event_register() {
    
    	$labels = array(
    		'name' => _x('Sport Event', 'post type general name'),
    		'singular_name' => _x('Event', 'post type singular name'),
    		'add_new' => _x('Add New', 'event'),
    		'add_new_item' => __('Add New Event'),
    		'edit' => __( 'Edit' ),
    		'edit_item' => __('Edit Event'),
    		'new_item' => __('New Event'),
    		'view_item' => __('View Event'),
    		'search_items' => __('Search Event'),
    		'not_found' =>  __('Nothing found'),
    		'not_found_in_trash' => __('Nothing found in Trash'),
    		'parent_item_colon' => ''
    	);
    
    	$args = array(
    		'labels' => $labels,
    		'public' => true,
    		'publicly_queryable' => true,
    		'show_ui' => true,
    		'query_var' => true,
    		'menu_icon' => get_stylesheet_directory_uri() . '/imgs/football.png',
    		'rewrite' => true,
    		'capability_type' => 'post',
    		'hierarchical' => false,
    		'menu_position' => null,
    		'supports' => array('')
    	  ); 
    
    	register_post_type( 'sport_event' , $args );
    }
    
    	register_taxonomy	("Teams", array("sport_event"),
    						array("hierarchical" => false,
    						"label" => "Teams",
    						"singular_label" => "Team",
    						"rewrite" => true));
    
    	register_taxonomy	("Opponents", array("sport_event"),
    						array("hierarchical" => false,
    						"label" => "Opponents",
    						"singular_label" => "Opponent",
    						"rewrite" => true));
    
    	add_action("admin_init", "admin_init");
    
    	function admin_init(){
    		add_meta_box("event_details-meta", "Event Details", "event_details", "sport_event", "normal", "low");
    		add_meta_box("event_teams-meta", "Event Teams", "event_teams", "sport_event", "normal", "low");
    		add_meta_box("event_post_game-meta", "Post Game", "event_post_game", "sport_event", "normal", "low");
    	}
    
    	function event_teams() {
    		global $post;
    		$custom = get_post_custom($post->ID);
    		$event_team = $custom["event_team"][0];
    		$event_opponent = $custom["event_opponent"][0];
    		$local_team = get_terms("Teams", "hide_empty=0");
    		$opponent = get_terms("Opponents", "hide_empty=0");
    		?>
    		<label>Team: </label>
    		<select name="event_team">
    		<!-- Get all featured teams and display them as options -->
    		<?php 
    
    		echo "<option style=\"background-color: #000; color: #fff;\" class='select_team' value='"
    			. $event_team . "' "
    			. ">"
    			. $event_team
    			. "</option>\n"; 
    
    		foreach ($local_team as $select_team) {
    			echo "<option class='select_team' value='" . $select_team->name . "'>" . $select_team->name . "</option>\n";
    		}
    		?>
    		</select>
    		<label>Opponent: </label>
    		<select name="event_opponent">
    		<!-- Get all opponents and display them as options -->
    		<?php 
    
    		echo "<option style=\"background-color: #000; color: #fff;\" class='select_team' value='"
    			. $event_opponent . "' "
    			. ">"
    			. $event_opponent
    			. "</option>\n"; 
    
    		foreach ($opponent as $select_team) {
    			echo "<option class='select_team' value='"
    			. $select_team->name . "' "
    			. ">"
    			. $select_team->name
    			. "</option>\n";
    		}
    		?>
    		</select>
    		<?php
    	}
    
    	function event_details(){
    		global $post;
    		$custom = get_post_custom($post->ID);
    		$event_date = $custom["event_date"][0];
    		$event_time = $custom["event_time"][0];
    		$territory = $custom["territory"][0];
    		$region = $custom["region"][0];
    		?>
    		<label style="font-weight:bold;">Event Date: </label>
    		<input type="text" id="datepicker" name="event_date" class="date" value="<?php echo $event_date; ?>" /><br />
    
    		<label style="font-weight:bold;">Event Time: </label>
    		<input type="text" id="timepickr" name="event_time" class="time" value="<?php echo $event_time; ?>" /><br />
    		<hr />
    		<label style="font-weight:bold;">Territory: </label><br /><?php $checked = $territory ?>
    		<input type="radio" name="territory" value="home" <?php if ($checked == "home") echo "checked" ?>/> Home<br />
    		<input type="radio" name="territory" value="away" <?php if ($checked == "away") echo "checked" ?>/> Away<br />
    		<hr />
    		<label style="font-weight:bold;">Region: </label><br /><?php $checked = $region ?>
    		<input type="radio" name="region" value="district" <?php if ($checked == "district") echo "checked" ?>/> District<br />
    		<input type="radio" name="region" value="non-district" <?php if ($checked == "non-district") echo "checked" ?>/> Non-district<br />
    
    		<?php
    	}

    Again, any insight would remove this one month roadblock from my to-do list.

  2. Mark / t31os
    Moderator
    Posted 3 years ago #

    See the example on the add_meta_box page.
    http://codex.wordpress.org/Function_Reference/add_meta_box#Example

    Of note, the lines refering to DOING_AUTOSAVE and checking for your custom nonce field, this helps determine if your custom inputs are doing the saving or if a WP routine, like the autosave is, you can then conditionalise your code around that.

    Related discussion:
    http://old.nabble.com/Automate-the-installation-of-WordPress-td26769469.html

    Related ticket:
    http://core.trac.wordpress.org/ticket/10744

    Hope that helps.... :)

  3. pszeinert
    Member
    Posted 3 years ago #

    We shall see. Thanks for digging those up. I honestly feel like I have run circles around this side of the internet for the past few weeks. It's nice to see some fresh material.

  4. Mark / t31os
    Moderator
    Posted 3 years ago #

    No problem, only took a few moments...

    I havn't used custom meta boxes myself, but have read discussions on the topic and always remembered the DOING_AUTOSAVE constant, so it gave me something specific to search for..

    http://www.google.com/search?q=wordpress+DOING_AUTOSAVE

    Gave me enough specificity to find the previous links... :)

  5. pszeinert
    Member
    Posted 3 years ago #

    I haven't made any changes to the code and am still reading through the add_meta_box example, but stepping through the routine has revealed that the Auto Draft is saved as soon as I "Add New," which I knew, but seeing that in the database tells me when I set the post_ID, I am not grabbing the correct DB entry and so it is creating a new post then updating the old Auto Draft with empty fields.

    I hope I can determine a routine to create/update the correct post_ID in the DB.

  6. Mark / t31os
    Moderator
    Posted 3 years ago #

    Like i said, not something i've worked with..... but is your code above that saves the data hooked onto save_post? (if not, shouldn't it be? - like in the example)

  7. pszeinert
    Member
    Posted 3 years ago #

    Mark, I appreciate the help thus far, I just want to make it clear before I continue that I have probably spent 40+ hours on this. I have been through many versions of the code and have refactored for various reasons at different times. I really don't like to ask for help until I have absolutely exhausted every method I can come up with or search for.

    Early on, I was able to save the custom fields to one post by using add_action ('save_post', 'save_details;) and could save the post_title by using the wp_insert_post($post) method to another. I found I could not add a wp_insert_post() call within the function because it would create a recursion and cause an infinite loop.

    At one point, I could stop it from adding 600 DB entries by getting the post_id set correctly, but it would still infinitely loop on that one post.

    That said...

    Currently, the code will not save either the custom fields or the post_title. It is only causing the Auto Save to transition from auto-save to publish.

    function save_details() {
    		if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
    			return $post_id;
    		}
    
    		// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
    		// to do anything
    		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;
    		} else {
    			if ( !current_user_can( 'edit_post', $post_id ) )
    			return $post_id;
    		}
    
    		global $post;
    
    		$event_team = $_POST["event_team"];
    		$event_opponent = $_POST["event_opponent"];
    		$event_date = $_POST["event_date"];
    
    		$my_post_title = ($event_team ." vs. " .$event_opponent ." - " .$event_date);
    		$my_post_name = sanitize_title($event_team ."-vs-" .$event_opponent ."-" .$event_date);
    
    		// Add the content of the form to $post as an array
    		$post = array(
    				'ID' => $post_ID, //Are you updating an existing post?
    				'post_content' => 'This is a custom post of the sport_event type. If you can see this text, something is wrong', //The full text of the post.
    				'post_name' => $my_post_name, // The name (slug) for your postet the status of the new post.
    				'post_title' => $my_post_title,
    				'post_type' => 'sport_event',
    				'post_status' => 'future',
    				'post_author' => 1
    			);
    
    		add_post_meta($post_id, "event_team", $_POST["event_team"]);
    		add_post_meta($post_id, "event_opponent", $_POST["event_opponent"]);
    		add_post_meta($post_id, "event_date", $_POST["event_date"]);
    		add_post_meta($post_id, "event_time", $_POST["event_time"]);
    		add_post_meta($post_id, "territory", $_POST["territory"]);
    		add_post_meta($post_id, "region", $_POST["region"]);
    		add_post_meta($post_id, "game_audio", $_POST["game_audio"]);
    		add_post_meta($post_id, "local_score", $_POST["local_score"]);
    		add_post_meta($post_id, "opponent_score", $_POST["opponent_score"]);
    
    		return $post_id;
    		return $post;
    	}
    
    	add_action ('save_post', 'save_details', 99, 2);
  8. pszeinert
    Member
    Posted 3 years ago #

    I like this code best because it is overwriting the Auto Save, but the recursion issues are back. I am assuming it is auto incrementing after the save and running again. Either I am not declaring the correct $post_id or I missed the code that is causing it to run multiple times.

    It could also be because I have the $post_id = wp_insert_post ($post), but I am still unsure how these routines operate.

    Frankly there are times that I am astounded any of this "works" at all.

    function save_details($post_id) {
    		if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && ($_POST['post_type'] == "sport_event")) {
    
    			global $post;
    
    			$event_team = $_POST["event_team"];
    			$event_opponent = $_POST["event_opponent"];
    			$event_date = $_POST["event_date"];
    
    			$my_post_title = ($event_team ." vs. " .$event_opponent ." - " .$event_date);
    			$my_post_name = sanitize_title($event_team ."-vs-" .$event_opponent ."-" .$event_date);
    
    			$_POST['post_title'] = $my_post_title;
    
    			// Add the content of the form to $post as an array
    			$post = array(
    				'ID' => $post_ID, //Are you updating an existing post?
    				'post_content' => 'This is a custom post of the sport_event type. If you can see this text, something is wrong', //The full text of the post.
    				'post_name' => $my_post_name, // The name (slug) for your post.
    				'post_title' => $my_post_title,
    				'post_type' => 'sport_event',
    				'post_status' => 'future',
    				'post_author' => 1
    			);
    
    			$post_id = wp_insert_post ($post);
    
    			add_post_meta($post_id, "event_team", $_POST["event_team"]);
    			add_post_meta($post_id, "event_opponent", $_POST["event_opponent"]);
    			add_post_meta($post_id, "event_date", $_POST["event_date"]);
    			add_post_meta($post_id, "event_time", $_POST["event_time"]);
    			add_post_meta($post_id, "territory", $_POST["territory"]);
    			add_post_meta($post_id, "region", $_POST["region"]);
    			add_post_meta($post_id, "game_audio", $_POST["game_audio"]);
    			add_post_meta($post_id, "local_score", $_POST["local_score"]);
    			add_post_meta($post_id, "opponent_score", $_POST["opponent_score"]);
    		}
    	}
    	add_action ('save_post','save_details');
  9. pszeinert
    Member
    Posted 3 years ago #

    Disregard the code in the last post. I had dirty code on my clipboard. There are a lot of issues that anyone can find. I am still refactoring and will update later.

  10. Mark / t31os
    Moderator
    Posted 3 years ago #

    If the example code works, maybe you could work your code into the example. At least that way you know you're building on top of a working code base?

  11. pszeinert
    Member
    Posted 3 years ago #

    Alright, took your suggestion, completely replaced the function.php with just the code from the example, and played in the sandbox for a while.

    I got a pretty good feel for what is going on and where.

    With the following code, I can create a new post, publish, and update.

    function save_details($post_id) {
    		if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && ($_POST['post_type'] == "sport_event")) {
    			// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
    			// to do anything
    
    			// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
    			// to do anything
    			if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
    			return $post_id;
    
    			$event_team = $_POST["event_team"];
    			$event_opponent = $_POST["event_opponent"];
    			$event_date = $_POST["event_date"];
    
    			$my_post_title = ($event_team ." vs. " .$event_opponent ." - " .$event_date);
    			$my_post_name = sanitize_title($event_team ."-vs-" .$event_opponent ."-" .$event_date);
    
    			// Add the content of the form to $post as an array
    			$post = array(
    				'ID' => $post_id, //Are you updating an existing post?
    				'post_content' => 'This is a custom post of the sport_event type. If you can see this text, something is wrong', //The full text of the post.
    				'post_name' => $my_post_name, // The name (slug) for your post.
    				'post_title' => $my_post_title,
    				'post_type' => 'sport_event',
    				'post_status' => 'future',
    				'post_author' => 1
    			);
    
    			update_post_meta($post_id, "event_team", $_POST["event_team"]);
    			update_post_meta($post_id, "event_opponent", $_POST["event_opponent"]);
    			update_post_meta($post_id, "event_date", $_POST["event_date"]);
    			update_post_meta($post_id, "event_time", $_POST["event_time"]);
    			update_post_meta($post_id, "territory", $_POST["territory"]);
    			update_post_meta($post_id, "region", $_POST["region"]);
    			update_post_meta($post_id, "game_audio", $_POST["game_audio"]);
    			update_post_meta($post_id, "local_score", $_POST["local_score"]);
    			update_post_meta($post_id, "opponent_score", $_POST["opponent_score"]);
    
    		}
    		return $post;
    	}
    	add_action ('wp_insert_post','save_details');

    ...and get something similar to this:

    Auto Draft Navasota Rattlers - 12 2010-08-28 05:00 pm Bryan - 10 away district

    I have been at this point many times. What I am trying to do is take the team names and the date of the event, string them together, and save it as the 'post_title'.

    I have to use wp_insert_post instead of save_post because save_post does not properly update the custom fields. Because of this, I can't call wp_insert_post within the function.

    I guess that means my current question is how can I save the $post(array) to the database where I am already saving the custom fields?

    On a side note, if I do add wp_insert_post($post) after I create the $post(array), it gets stuck in a loop, but everything in the array is saved just once and no custom fields are saved after.

  12. Mark / t31os
    Moderator
    Posted 3 years ago #

    Having not worked with custom meta boxes i can't think of anything further to suggest unfortunately, other than doing what i do, and just keep searching, looking at examples, testing code, etc, etc..

    Perhaps another forum user who has experience with meta boxes can advise further (this is the hacks forum after all).

  13. pszeinert
    Member
    Posted 3 years ago #

    The details of my project dictated that I would have to settle for half of the equation. The title will not update on the appropriate post and I end up with two posts, one with details and one with the proper title.

    Since this is being used in house, I'm okay with it saying "Auto Draft."

    Currently the code has a lot of commented out sections so I can revisit this before next football season.

    if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && ($_POST['post_type'] == "sport_event")) {
    
    		function save_details($post_ID) {
    			//if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && ($_POST['post_type'] == "sport_event")) {
    
    				// verify if this is an auto save routine. If it is our form has not been submitted, so we dont want
    				// to do anything
    				if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
    				return $post_ID;
    
    				update_post_meta($post_ID, "event_team", $_POST["event_team"]);
    				update_post_meta($post_ID, "event_opponent", $_POST["event_opponent"]);
    				update_post_meta($post_ID, "event_date", $_POST["event_date"]);
    				update_post_meta($post_ID, "event_time", $_POST["event_time"]);
    				update_post_meta($post_ID, "territory", $_POST["territory"]);
    				update_post_meta($post_ID, "region", $_POST["region"]);
    				update_post_meta($post_ID, "game_audio", $_POST["game_audio"]);
    				update_post_meta($post_ID, "local_score", $_POST["local_score"]);
    				update_post_meta($post_ID, "opponent_score", $_POST["opponent_score"]);
    				update_post_meta($post_ID, "game_notes", $_POST["game_notes"]);
    
    			}
    
    		//}
    
    		add_action ('wp_insert_post','save_details',99);
    
    		/*$event_team = $_POST["event_team"];
    		$event_opponent = $_POST["event_opponent"];
    		$event_date = $_POST["event_date"];
    
    		$my_post_title = ($event_team ." vs. " .$event_opponent ." - " .$event_date);
    		$my_post_name = sanitize_title($event_team ."-vs-" .$event_opponent ."-" .$event_date);
    
    		// Add the content of the form to $post as an array
    		$post = array(
    			'ID' => $post_ID, //Are you updating an existing post?
    			'post_content' => 'This is a custom post of the sport_event type. If you can see this text, something is wrong', //The full text of the post.
    			'post_name' => $my_post_name, // The name (slug) for your post.
    			'post_title' => $my_post_title,
    			'post_type' => 'sport_event',
    			'post_status' => 'future',
    			'post_author' => 1
    		);
    
    		wp_update_post($post);*/
    
    	}

    If you want to see what visitors will see, you can check it out at playbyreplay.com. I'm not linking it because I'm not one for shameless plugs.

    Thanks for all your help Mark. I'm sure some other project I work on in the future will put the cherry on top of this one.

  14. wpAdm
    Member
    Posted 3 years ago #

    Hello
    I too want to change the title, but I get an infinite loop and apache craches.
    How did you decide this problem?

  15. kangaechigai
    Member
    Posted 3 years ago #

    wpAdm, you might want to try the title_save_pre filter hook (and maybe others like name_save_pre).
    e.g.:

    add_filter( 'title_save_pre', 'change_the_title' );
    function change_the_title($title_to_ignore) {
    	$real_title = "whatever you want";
    	return $real_title;
    }

    It will run just before the post is saved to the database, but since it only filters instead of actually performing any "action", it won't cause an infinite loop. You'll still want to attach to save_post for actually saving any custom fields, but you'll be able to pull those fields from the $_POST again within the filter if you need them for generating your custom title.

  16. Nowell VanHoesen
    Member
    Posted 3 years ago #

    Have you thought about using $wpdb->query()?

    I know this would not be ideal, but after racking my brain and too many hours trying to accomplish the same task I think I am going to create my own query with a check to make sure it's not already set.

    The following works. It is in a function that is called with a save_post add_action.

    $new_post_title = 'new title';
    if ( $new_post_title !== $post->post_title ) {
    	$new_post_name = sanitize_title( $new_post_title );
    	$wpdb->query( $wpdb->prepare( "update $wpdb->posts set post_title = '$new_post_title', post_name = '$new_post_name' where ID = $post->ID" ) );
    }

    HTH

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.