1

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.