Unable to save Query Vars with a post - wordpress

I'm trying to save Query Vars to a post for later retrieval.
I'm using permalinks in this format: domain.com/%category%/%postname%/
Example:
I create a following page
domain.com/page-003/
I add Query Var called email to the page
add_query_arg('email', 'test#abc.com', 'domain.com/page-003/')
Now when I call
get_permalink($post_id);
I get
domain.com/page-003/
Instead of
domain.com/page-003/?email=test#abc.com
What am I missing? Aren't Query Vars saved with a post?

You want to save some meta data which you want to restore later on and add as query arg into the URL.
You need to first save it as post_meta like e.g. when you save post with that data. You use:
<?php update_post_meta(get_the_ID(), 'email_address', 'abc#mail.com'); ?>
More details: https://codex.wordpress.org/Function_Reference/update_post_meta
Then during the retrieval, you may hook into a HOOK early on like template_redirect or earlier of the post you can get post_meta to get the email and then add to query arg:
<?php $email = get_post_meta( get_the_ID(), 'email_address' ); ?>
Then
esc_url( add_query_arg( 'email', $email, get_permalink( get_the_ID() ) ) );
Something like that, code is untested, I just wrote here, you may please read detailed doc in codex for each function used above.
Update: How to update/fill Ninja form field from Meta Value:
add_filter( 'ninja_forms_render_default_value', 'wm_the_value' , 10 , 3);
function wm_the_value( $default_value, $field_type, $field_settings ) {
if( 'textbox' == $field_type && in_array('ref' , $field_settings)){
$default_value = get_post_meta(get_the_ID(),'_listing_mls', true);
}
return $default_value;
}
'ref' is field name in Ninja form.
'_listing_mls' is meta_key name from WP database.
Hope it works for you.

Related

How to change the default structure generation of single post permalinks?

I want to change the output of the_permalink() function and the likes. So, I don't want to change the mermalink structure for all the post types, only the 'post' post type, and only the single page.
I already changed the rewrite rules so that
mysite.com/news/2016/the-news-title
will drive the user to the single post page template and display content properly. Fine.
Now, as I said, I want the_permalink() function to generate links with that structure.
How could I do it?
I didn't find a proper solution but you can generate your permalink here for post type post you have $post WP_Post Object ..
Why use get_post() because post_name (permalink) is saved in this field and it will always unique.
function edit_the_permalink($permalink) {
$post = get_post(array('post_name' => $permalink));
if( $post->post_type == 'post' ) {
// Override your permalink here for post_type = `post`
echo '<pre>';print_r($post);echo '</pre>';
$permalink = '';
return $permalink;
}
}
add_filter('the_permalink', 'edit_the_permalink', 10, 1);
Ok following Noman indications, I can post my own answer. I could the 'the_permalink' filter and modify the output if post_type == 'post'. The basic code:
add_filter('the_permalink', 'edit_the_permalink', 10, 2);
function edit_the_permalink($permalink, $post) {
// you should pass the post object when calling the_permalink()
if(is_object($post) && $post->post_type == 'post'){
// [...do the magic...]
return $permalink;
}
}
Please note that both the_permalink() and get_permalink() (alias get_the_permalink()) accept the $post argument and you should pass it as a post object.
Also, note that you can do pretty much the same with the post_type_link filter if you want modify the custom post types permalink generation (output of get_post_permalink()). In this case the callback will receive 4 parameters: $post_link, $post, $leavename, $sample.

update custom post custom field value when post is saved in wp-admin

How to update custom post custom field value when post is saved in admin?
I have tried to use this in misc.php for admin section:
add_action('pre_post_update', 'do_something_with_a_post');
function do_something_with_a_post($id) {
global $post;
update_post_meta($id, 'ct_Course_Dur_text_d19c', 'test12');
)
But it is not working.
You may try this (Using save_post hook), paste this code in your functions.php file
function save_cpt_metadata($id, $post)
{
if($post->post_type != 'your_custom_post_type') {
return;
}
update_post_meta($id, 'ct_Course_Dur_text_d19c', sanitize_text_field( $_POST['your_custom_field'] ) );
}
add_action('save_post', 'save_cpt_metadata');
In this example sanitize_text_field( $_POST['your_custom_field'] ) is would be actually the cstom field on your form but you may use any hard coded data, replace the your_custom_post_type with your real custom post type.

Wordpress get_post_meta does not return when using variable

I'm trying to get a plugin to read the post metadata of an attachment, and use it to update the content of the post it is attached to. I'm using the following in my themes function.php:
add_action( 'afip_created_post', 'get_desc', 10, 2 );
function get_desc( $post_id, $attachment_id ) {
$postmeta = get_post_meta ($attachment_id, '_wp_attachment_metadata', true);
$meta = $postmeta['image_meta'];
$mmwwdesc = $meta['description'];
wp_update_post( array( 'ID' => $post_id, 'post_content' => $mmwwdesc ) );
}
and then using this line in the plugin to hook the function
do_action( 'afip_created_post', $new_post_id, $post_id );
If I fill in the varibale "$attachment_id" with a number from another post i.e "15," I get the description inserted into the published post. If I change the output to wp_update_post( array( 'ID' => $post_id, 'post_content' => $attachment_id ) ); I get the id number echoed in the body of the published post. I'm don't understand why the original code does not work, since $attachment_id seems to be properly defined. I'm just a beginner with php. Is there something obvious that I'm doing wrong? Is the variable $attachment_id being echoed when it should be returned, or something technical like that?
Background: I'm using two wordpress plugins, one called Media Metadata Workflow Wizard (MMWW), and the other called Automatic Featured Image Post (AFIP). MMWW extracts the image metadata and writes it to the database as post meta. AFIP creates new posts using uploaded media, and attaches each image to a post, setting it as the post thumbnail. I don't think its an issue of the metadata not being ready when the function is called, because AFIP creates the post after the media has been uploaded, and had its meta written to the database. I'm also hooking my function as an update to the post, after it has already been created.
I've done extensive searching, and trial and error with no success. Can anybody help me out?
Thanks!
I think your issue here is that the get_post_meta function is returning blank in functions.php. The way to deal with this issue is to use a MYSQL query with wordpress to return the data in your psot meta.
First you need the global $wpdb object so at the start of your function write: global $wpdb;
Then you need to do the get_post_meta action using mysql and the $wpdb object:
$postmeta = $wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta" WHERE meta_key = '_wp_attachment_metadata' AND post_id = $attachment_id");
Replace your get_post_meta line with the wpdb query and you should be fine.

How can I add/update post meta in a admin menu page?

I wanted to create a plugin to batch manage posts' custom field data. I know I can add post meta by adding a meta box in the post edit screen and using add_action('save_post', 'function_to_update_meta') to trigger add meta functions.
But I don't know how to trigger the add_post_meta function in an admin menu page (such as a custom admin menu). How to do that?
Thank you in advance!
The example given in Wordpress' codex is probably the best and most secure in the way of processing information:
Add Meta Box
Copy and paste it and then fiddle around with it to get a good idea on how to control your posts and pages.
The nice part is that you don't need to worry about checking if you need to Add vs Update a given Post Meta field. Using Update Post Meta will ensure that the proper action is taken for you, even if the field doesn't exist.
The same goes for Update Option if you want to add some global controls that your plugin/theme might use.
BREAKDOWN EXAMPLE:
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
These are the action hooks. The first one is executed when meta boxes are being populated within the post editor, and the second is executed when a post is added OR updated.
function myplugin_add_custom_box()
{
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'page'
);
}
This function is called by the 'add_meta_boxes' action hook. Notice the name of the function and the second argument of the action hook are exactly the same. This registers your meta boxes, which post types they're supposed to appear, and what callback is used to generate the form contained inside.
function myplugin_inner_custom_box( $post )
{
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
$value = get_post_meta($post->ID, 'myplugin_new_field') ? get_post_meta($post->ID, 'myplugin_new_field') : 'New Field';
echo '<label for="myplugin_new_field">';
_e("Description for this field", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.$value.'" size="25" />';
}
This is the function that is called by the registered meta boxes to generate the form automatically. Notice how the function is called 'myplugin_inner_custom_box' and the 3rd argument in your meta box registration is also called 'myplugin_inner_custom_box'.
The wp_nonce_field() generates a hidden field in your form to verify that data being sent to the form actually came from Wordpress, and can also be used to end the function in case other plugins are using the 'save_post' action hook.
Notice also that the $post object is being passed in as an argument. This will allow you to use certain properties from the post object. I've taken the liberty of checking to see if there is get_post_meta() returns anything with the given post ID. If so, the field is filled with that value. If not, it is filled with 'New Field'.
function myplugin_save_postdata( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = $_POST['myplugin_new_field'];
update_post_meta($post_id, 'myplugin_new_field', $mydata);
}
This is the function that is called by the 'save_post' action hook. Notice how the second argument of the second action hook and this function are both called 'myplugin_save_postdata'. First, there are a series of verifications our plugin must pass before it can actually save any data.
First, we don't want our meta boxes to update every time the given post is auto-updating. If the post is auto-updating, cancel the process.
Secondly, we want to make sure the nonce data is available and verify it. If no nonce data is available or is not verified, cancel the process.
Thirdly, we want to make sure the given user has the edit_page permission. The function first checks the post type, and then checks the appropriate permission. If the user does not have that permission, cancel the process.
Lastly, our plugin has finally been verified and we want to save the information. I took the liberty of adding in the final update_post_meta() line to show you how it all comes together.
Notice how $post_id was passed into the function as an argument. This is one of the pieces needed for the update_post_meta() function. The key was named 'myplugin_new_field' and the value of that metadata is now saved as whatever you input into that custom input field in your custom meta box.
That's about as easy as I can explain the whole process. Just study it, and get your hands dirty with code. The best way to learn is through application rather than theory.
The answer was from the same question I asked somewhere else
And I created my version of example
I added some console.log function for testing, but this is basically doning the same thing as #Chris_() answer:
Menu callback function to generate menu content (PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, 'your_key', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
Then the javascript to print on the admin side (javascript, don't forget to include a jquery library):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log('Submit Function');
var postMeta = $('input[name="1"]').val();
console.log(postMeta);
var postID = 1;
var button = $('input[type="submit"]');
button.val('saving......');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: 'POST',
url: ajaxurl,
success: function( response ) { console.log('Well Done and got this from sever: ' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
Then the PHP function handle update_post_meta (PHP):
add_action( 'wp_ajax_update_meta', 'my_ajax_callback' );
function my_ajax_callback() {
$post_id = $_POST['post_id'];
$post_meta = $_POST['post_meta'];
update_post_meta( $post_id, 'your_key', $post_meta );
echo 'Meta Updated';
die();
} // end of my_ajax_callback()

wp_update_post make custom field values disappear (Wordpress)

I'm trying to update the post content in one of my post through the wp_update_post function. I have read the documentation here: http://codex.wordpress.org/Function_Reference/wp_update_post
And if I get it right I just need to send the post ID and the post content I want to update with - just like in the example - and this should be the only thing that will change. Although my custom fields that I have attached to this post disappears, strange enough.
I have the following code that I pass on:
if(isset($_POST['submit'])){
$the_post = array();
$the_post['ID'] = $_POST['id'];
$the_post['post_content'] = $_POST['recension'];
// Update the post into the database
wp_update_post( $the_post );
}
How come this happen and how do I solve it?
This is because when you are updating the post the *wp_insert_post* function is used and there is "save_post"(1) action hook which is usually used for saving custom fields data.
The standard way to add/update post meta is something like this:
$post_meta['_mymeta'] = $_POST['_mymeta'];
// Add values of $events_meta as custom fields
foreach ($events_meta as $key => $value) { // Cycle through the $post_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
if($value && $value != get_post_meta($post->ID, $key, TRUE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} elseif($value && get_post_meta($post_id, $key, TRUE) == "") { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value, TRUE);
}
if(!$value) delete_post_meta($post->ID, $key, get_post_meta($post->ID, $key, TRUE)); // Delete if blank
}
...as you can see it is checking for *$_POST* data and if it is empty or not set it updates your meta value with empty data or deletes it completely.
I suppose you should use database update function or some other API function to update post fields...for example this piece of code will update your post menu order:
$wpdb->update( $wpdb->posts, array( 'menu_order' => 5 ), array( 'ID' => $post->ID ) );
(1) Runs whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. Action function arguments: post ID.
To avoid that behavior set false as third parameter.
It deactivates the "after insert hooks".

Resources