Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Liam Maclachlan
Liam Maclachlan
22,805 Points

How can I update post meta on plugin activation?

This is just some example code:

<?php 

function my_function_to_run() {
    update_post_meta( 12, 'audit_id', 5 )
}

register_activation_hook( __FILE__, 'my_function_to_run' ); 

?> 

But I can't seem to find a way to get update_post_meta to work on plugin activation! Any ideas?

1 Answer

Liam Maclachlan
Liam Maclachlan
22,805 Points

And now it works!! I must have had an error in my code somewhere... Either way, this code worked for me once I got home...

<?php
function my_function_to_run() {

    $args = array(
            'post_type' => 'page',
            'meta_query' => array(
                    array(
                            'key' => 'audit_id',
                            'compare' => 'NOT EXISTS',
                        )
                )
        );

    $posts = get_posts($args);

    foreach ($posts as $post ) {
        add_post_meta( $post->ID, 'audit_id', 1 );
        echo '1';
    }



}

register_activation_hook( __FILE__, 'my_function_to_run' ); 
?>

The first time it ran, I got a 2 char error (the echo in the foreach loop) on the plugin screen. The second time, nothing (no posts returned for the loop).. I will come back if I ever find out what the problem was :)