• Resolved erfan_atp

    (@erfan_atp)


    Hi. I want to send mail to a specific email on publishing a post in a special category, not all. I fund this code for functions.php but it should be complete to do my goal.

    function send_mails_on_publish( $new_status, $old_status, $post ) {
        if ( $old_status != 'publish' && $new_status == 'publish' ) {
            // Post is published
        }
    }
    add_action( 'transition_post_status', 'send_mails_on_publish', 10, 3 );

    Can You Help Me?

Viewing 4 replies - 1 through 4 (of 4 total)
  • J M

    (@hiphopinenglish)

    Here’s an example modified from the example on the Codex for the save_post hook:

    <?php
    function erfans_new_post_email( $post_id ) {
    
    	// If this is just a revision, don't send the email.
    	if ( wp_is_post_revision( $post_id ) )
    		return;
    
    	$category = 'x'; // Category ID, name or slug. You can use an array to pass more than one Category
    
    	if ( !in_category ( $category, $post_id ) ) // If the post is not in your required category/s
    		return;
    
    	$post_title = get_the_title( $post_id );
    	$post_url = get_permalink( $post_id );
    	$subject = 'A post has been updated';
    
    	$message = "A post has been updated on your website:\n\n"; // You can edit the message body using content from the post
    	$message .= $post_title . ": " . $post_url;
    
    	// Send email to specific address.
    	wp_mail( 'erfan@example.com', $subject, $message ); // The email address you wish to send to
    }
    add_action( 'save_post', 'erfans_new_post_email' );
    ?>
    Thread Starter erfan_atp

    (@erfan_atp)

    tnx. but i want to send mail when it published, not when it’s state is ‘pending’.

    J M

    (@hiphopinenglish)

    OK, so you’ll need to add a conditional line to check the post status. You should use get_post_status. See if you can work out how to use it. Report back here if you get stuck.

    Thread Starter erfan_atp

    (@erfan_atp)

    I used this:

    function post_published( $new_status, $old_status, $post ) {
        if ( $old_status != 'publish' && $new_status == 'publish' ) {
            // Post is published
            $category = array('3','4','5','6','7','8'); // Category ID, name or slug. You can use an array to pass more than one Category
    		if ( !in_category ( $category, $post ) ) // If the post is not in your required category/s
    			return;
    wp_mail( $to, $subject, $message ); // The email address you wish to send to
        }
    }
    add_action( 'transition_post_status', 'post_published', 10, 3 );

    It works!
    Thank You hiphopinenglish !

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘How to send mail on publish a specific category’ is closed to new replies.