Programmatically adding posts

时间:2012-11-16 作者:Anton Abramov

我将要创建一个解析器,它将插入新的自定义帖子。所以,这很简单

global $user_ID;
$new_post = array(
    \'post_title\' => \'My New Post\',
    \'post_content\' => \'Lorem ipsum dolor sit amet...\',
    \'post_status\' => \'publish\',
    \'post_date\' => date(\'Y-m-d H:i:s\'),
    \'post_author\' => $user_ID,
    \'post_type\' => \'post\',
    \'post_category\' => array(0)
);
$post_id = wp_insert_post($new_post);
但我在创建永久链接时有一些额外的逻辑。

function my_post_type_link_filter_function( $post_link, $id = 0, $leavename = FALSE ) {
    if ( strpos(\'%dgor%\', $post_link) === \'FALSE\' && strpos(\'%znak%\', $post_link) === \'FALSE\' ) {
        return $post_link;
    }
    $post = get_post($id);
    if ( !is_object($post) || $post->post_type != \'goroskop\' ) {
        return $post_link;
    }
    $day = wp_get_object_terms($post->ID, \'gday\');
    $month = wp_get_object_terms($post->ID, \'gmonth\');
    $year = wp_get_object_terms($post->ID, \'gyear\');
    if (  !$day || !$month || !$year ) {
        return $post_link;
    }
    $post_link = str_replace(\'%gday%\', $day[0]->slug, $post_link);
    $post_link = str_replace(\'%gmonth%\', $month[0]->slug, $post_link);
    return str_replace(\'%gyear%\', $year[0]->slug, $post_link);
}
add_filter(\'post_type_link\', \'my_post_type_link_filter_function\', 1, 3);
因此,我需要根据自定义分类法替换permalink结构中的一些标记。

问题是:Is there any way to invoke this logic programmatically while inserting new custom post?

1 个回复
SO网友:Mubbashar
add_action( \'publish_post\', \'run_when_post_published_first_time\',10,2 );
function run_when_post_published_first_time($post_id, $post)
{
// Checks whether is post updated or published at first time.
if ($post->post_date != $post->post_modified) return;

// Place here your code
}

from http://wordpress.org/support/topic/new-post-hook

结束

相关推荐

widgetlogic and permalinks

我试图使用widgetlogic在某些页面上有条件地显示菜单。每个菜单都使用如下标记is_page(array(\"Page Name\", \"Page Name 2\" ...)), 在我尝试更改permalinks之前,它一直工作得很好(因此所有菜单都会从各自的页面中消失)。我做错什么了吗?是否有解决方法?