4

I made a custom post type and on saving its additional data I want to check if I a published post exists by its name. It works alright if there is, but I would like to throw some notice if article is not found.

    $post_exists = $wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $_POST['article_name'] . "' AND post_type = 'post'", 'ARRAY_A');
    if($post_exists)
        update_post_meta($id, 'article_name', strip_tags($_POST['article_name']));
    else
        ???

I noticed there is http://codex.wordpress.org/Class_Reference/WP_Error but I dont think that is what I want since debugging is set to false?. Error could be anything - some usual notice would be fine, but even simple javascript alert could be good. Currently it tells me that the post is saved with green lights which doesnt seem right http://s1.postimg.org/kmjjjvuvj/image.jpg

2 Answers 2

5

You can use admin_notices hook http://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices

For example:

function ravs_admin_notice() {
    ?>
    <div class="error">
        <p><?php _e( 'Article with this title is not found!', 'my-text-domain' ); ?></p>
    </div>
    <?php
}

on publish_{your_custom_post_type} hook http://codex.wordpress.org/Post_Status_Transitions

function on_post_publish( $ID, $post ) {
    // A function to perform actions when a {your_custom_post_type} is published.
    $post_exists = $wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $_POST['article_name'] . "' AND post_type = 'post'", 'ARRAY_A');
    if($post_exists)
        update_post_meta($id, 'article_name', strip_tags($_POST['article_name']));
    else
       add_action( 'admin_notices', 'ravs_admin_notice' );
}
add_action(  'publish_{your_custom_post_type}',  'on_post_publish', 10, 2 );
2

The notice is easy to set via the hook admin_notices. You can set on each page a message via this hook.

function my_admin_notice() {
    ?>
    <div class="updated">
        <p><?php _e( 'Updated!', 'my-text-domain' ); ?></p>
    </div>
    <?php
}
add_action( 'admin_notices', 'my_admin_notice' );

Ping this hook on your else construct.

else
    add_action( 'admin_notices', 'my_admin_notice' );

Check inside the function my_admin_notice() the post type or use this only on the publish_{custom_post_type} Hook.

The color is dependence from the css class.

enter image description here

You find much more about classes and html in this helper plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.