Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Problem setting terms and custom fields on post save WordPress

  • SOLVED

I have an action hooked up to title_save_pre, adding a custom field and custom taxonomy term based on the title of the post.

It almost works, but has two problems:
<strong>Problem 1:</strong> It adds the term to the taxonomy, but it does not connect it to the post. It seems to connect it to the revision or something.
<strong>Problem 2:</strong> When the title updates, the custom field does not update until after saving twice.

Gist is here: http://bit.ly/TKY7kN

Answers (3)

2012-09-02

Dbranes answers:

you could try turning off the revisions in your wp-config.php :

define('WP_POST_REVISIONS', 0 );

but it is not clear why you are using the 'title_save_pre' hook to do this.

Can you use a different hook, like 'save_post' ?


<strong>Update 2</strong>: here is my suggestion using the 'save_post' hook

[[LINK href="http://pastebin.com/hE0g58qC"]]http://pastebin.com/hE0g58qC[[/LINK]]


web559 comments:

Thanks for looking into this. Your version successfully tags the term, but only after saving twice. And as before, the custom field does not get updated until the second save.

Is $title perhaps reflecting the version of the title that's in the database, as opposed the new version that is being submitted?


web559 comments:

Also—unfortunately it's not an option to turn off revisions, as I use them.


Dbranes comments:

I just updated the code above, using $_POST['post_title']

see http://pastebin.com/hE0g58qC


web559 comments:

$_POST['post_title'] fixed it. Is there an native API way to get the post data? I've rarely dealt directly with $_GET and $_POST in WP and usually use API functions like get_query_var(), which are already escaped/sanitized etc.


Dbranes comments:

ok, great ;-)


You could consider using functions like:

esc_html(), esc_attr() , wp_kses()

to escape the input.

$_REQUEST should handle both cases (i.e. POST/GET)


ps:

I'm not sure if get_query_var is accessible inside the 'save_post' hook function, even if you use the global $wp_query.
Mabye you could construct a new temporary WP query object to see if it offers the escape/sanitizing, by using

$new_query = new WP_Query( $args );

inside the hook function.

http://codex.wordpress.org/Class_Reference/WP_Query


2012-09-02

Arnav Joy answers:

Sorry but I not understood what you want to achieve ? please explain.

2012-09-02

Francisco Javier Carazo Gil answers:

Give me access via FTP and I will try to solve it. Send PM.