Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 :)