Wordpress:无法检索functions.php中的帖子内容

时间:2014-02-13 11:22:57

标签: php wordpress email

我写了一些内容,一旦发布,就会向我发送一封包含帖子内容的电子邮件。我可以从帖子中获取标题,类别,作者和永久链接,并在邮件中显示,但不是内容!

<?php

// Function that runs when a post is published
function run_when_post_published() {

    $post = get_post($post_id);
    $author = get_userdata($post->post_author);
    $category = get_the_category();
    $author_id = $post->post_author;
    $author = get_the_author_meta( 'nickname', $author_id ); 
    $title = get_the_title();
    $permalink = get_permalink();
    $my_content = get_the_content();

    $email_subject = '(' . $category[0]->cat_name . ') Case fra kundelogg: ' . $title;
    $message = $my_content . 'Written by: ' . $author . ', Link: ' . $permalink;
    $headers = 'From: CRM System <mail@mail.com>';

// Advanced custom field to check if post is supposed to be mailed or not
if( !empty($_POST['fields']['field_52fc8615d3526'] ) ) {

    $email = 'myemail@mycompany.com';
    wp_mail( $email, $email_subject, $message );

}
else { // Do nothing }

}

// Makes sure email only gets sent the first time a post is published
add_action('new_to_publish', 'run_when_post_published');        
add_action('draft_to_publish', 'run_when_post_published');      
add_action('pending_to_publish', 'run_when_post_published');
?>

我已尝试过多种方法让内容显示在邮件中,在某些情况下,我实际上会显示两到六个字符。但不是全部内容。这就像内容被随机截断,但事实并非如此。上面代码中带有get_the_content()的示例虽然没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

将$ message = ...中的$ my_content替换为apply_filters( 'the_content', $post->post_content )

$message = apply_filters( 'the_content', $post->post_content ) . ' Written by: ' . $author . ', Link: ' . $permalink;

删除$post = get_post( $post_id );

添加$ post作为函数参数。

在下面的最终版本中,我已经进行了上面列出的更改,但是我没有尝试清理代码。这是完整版:

<?php

// Function that runs when a post is published
function run_when_post_published( $post ) {
    $author = get_userdata($post->post_author);
    $category = get_the_category();
    $author_id = $post->post_author;
    $author = get_the_author_meta( 'nickname', $author_id ); 
    $title = get_the_title();
    $permalink = get_permalink();

    $email_subject = '(' . $category[0]->cat_name . ') Case fra kundelogg: ' . $title;
    $message = apply_filters( 'the_content', $post->post_content ) . 'Written by: ' . $author . ', Link: ' . $permalink;
    $headers = 'From: CRM System <mail@mail.com>';

    // Advanced custom field to check if post is supposed to be mailed or not
    if( !empty($_POST['fields']['field_52fc8615d3526'] ) ) {

        $email = 'myemail@mycompany.com';
        wp_mail( $email, $email_subject, $message );

    }
}