【问题标题】:Assigning a custom field whenever a post is created每当创建帖子时分配自定义字段
【发布时间】:2013-07-17 12:59:17
【问题描述】:

我正在尝试将自定义字段添加到包含帖子摘要的所有帖子中。我创建了一个名为“post-summary”的自定义字段。我想要做的是自动为这个自定义字段赋值。

<?php 
$value = somefunction($content);
add_post_meta( {{current post id}} , 'post-summary', $value , true ) || update_post_meta( {{current post id}} , 'post-summary', $value ); 

每当发布新帖子时如何应用此功能?

【问题讨论】:

    标签: php wordpress cron


    【解决方案1】:

    使用wp_insert_post 钩子,它基本上是save_post,仅在首次创建帖子时触发。而update_post_meta实际上会添加自定义字段值,你不需要先做add_post_meta。

    add_action( 'wp_insert_post', 'set_your_default_summary' );
    
    function set_your_default_summary( $post_id ) {
      // Check to make sure this post is for the right post type
      if( 'your_post_type' == get_post_type( $post_id ) ) {
    
          $post = get_post($post_id);
    
          $value = somefunction($post->post_content);
    
                // Make sure this isn't just a revision auto-saving
            if( !wp_is_post_revision( $post_id ) ) {
                update_post_meta( $post_id, 'post_summary', $value );
            }
    
           return $post_id;
        }
    }
    

    【讨论】:

    • 您遇到的错误是什么。我从当前正在工作的functions.php文件中复制并粘贴了它。
    • 它没有显示任何错误,因为我正在使用 MAMP 在本地开发,但它返回一个致命错误,因为一切都停止工作!
    • 我假设您正在替换我的示例中的所有适当值(即“your_post_type”替换为帖子类型的名称,somefunction() 替换为您的函数名称)。
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多