問題描述
我想有一個連結來建立一個新的職位,也設定類別。
我試過 wp-admin/post-new.php?post_category=12 和 wp-admin/post-new.php?cat=12,但都沒有工作。我也嘗試使用該名稱而不是該類別的 id; 這也沒有影響。
如何建立一個預設類別的新帖子的連結?
最佳解決方案
GitHub 上的戴維·詹姆斯·米勒 (Dave James Miller) 為我定了一個。沒有一個工作來自我,我只是把他的程式碼包裝成一個 plguin,因為它的廣告效果完美:
<?php
/**
* Plugin Name: Set default category from url parameter
* Plugin URI: https://gist.github.com/davejamesmiller/1966543
* Description: enables you to setup new post links with the post_title, category and tags in the url: <code><a href="http://<?=%20esc_attr(admin_url('post-new.php?post_title=Default+title&category=category1&tags=tag1,tag2'))%20?>">New post</a></code>
* Version: 0.0.1
* Author: davejamesmiller
* Author URI: https://gist.github.com/davejamesmiller
*/
// I used this code to automatically set the default post title, category and
// tags for a new WordPress post based on which link was clicked. It could also
// be tweaked to hard-code the values instead of using request parameters.
add_filter('wp_get_object_terms', function($terms, $object_ids, $taxonomies, $args)
{
if (!$terms && basename($_SERVER['PHP_SELF']) == 'post-new.php') {
// Category - note: only 1 category is supported currently
if ($taxonomies == "'category'" && isset($_REQUEST['category'])) {
$id = get_cat_id($_REQUEST['category']);
if ($id) {
return array($id);
}
}
// Tags
if ($taxonomies == "'post_tag'" && isset($_REQUEST['tags'])) {
$tags = $_REQUEST['tags'];
$tags = is_array($tags) ? $tags : explode( ',', trim($tags, " ntrx0B,") );
$term_ids = array();
foreach ($tags as $term) {
if ( !$term_info = term_exists($term, 'post_tag') ) {
// Skip if a non-existent term ID is passed.
if ( is_int($term) )
continue;
$term_info = wp_insert_term($term, 'post_tag');
}
$term_ids[] = $term_info['term_id'];
}
return $term_ids;
}
}
return $terms;
}, 10, 4);
次佳解決方案
鉤入 wp_insert_post,測試 auto-draft 的釋出狀態,以及 GET 引數的 URL 。
但是首先我們需要一個幫助函式來獲取和清理 GET 引數:
/**
* Set default category.
*
* @wp-hook pre_option_default_category
* @return string Category slug
*/
function t5_get_default_cat_by_url()
{
if ( ! isset( $_GET['post_cat'] ) )
return FALSE;
return array_map( 'sanitize_title', explode( ',', $_GET['post_cat'] ) );
}
現在 auto-draft 處理程序:
add_action( 'wp_insert_post', 't5_draft_category', 10, 2 );
/**
* Add category by URL parameter to auto-drafts.
*
* @wp-hook wp_insert_post
* @param int $post_ID
* @param object $post
* @return WP_Error|array An error object or term ID array.
*/
function t5_draft_category( $post_ID, $post )
{
if ( ! $cat = t5_get_default_cat_by_url()
or 'auto-draft' !== $post->post_status )
return;
// return value will be used in unit tests only.
return wp_set_object_terms( $post_ID, $cat, 'category' );
}
僅當 get_default_post_to_edit()被呼叫第二個引數 $create_in_db 設定為 TRUE 時,這是有效的。要抓住其他情況,您必須過濾選項 default_category:
add_filter( 'pre_option_default_category', 't5_get_default_cat_by_url' );
現在可以使用引數 post_cat 傳遞一個逗號分隔的類別 lug separated 列表:
也可以看看:
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
