我正在开发一个系统,强制用户(不熟悉wp)在创建新帖子之前选择一个类别,然后添加一些适当的html布局样式来帮助他们。
如果选择类别“x”,则以下代码有效。如何对其进行调整以应对两种不同类别的情况?
所需人员代码:
如果新帖子属于X类:添加此html如果新帖子属于Y类:请添加此html如果新帖子是任何其他类别:添加此html现有代码-如果类别为“X”,则在新帖子中插入一些html:
// This function will only be called when creating an empty post,
// via `get_default_post_to_edit()`, called in post-new.php
function wpse14403_wp_insert_post( $post_id )
{
wp_set_post_categories( $post_id, $_REQUEST[\'category_id\'] );
}
add_filter( \'default_content\', \'wpa70073_default_products_content\' );
function wpa70073_default_products_content( $content ) {
// change this to your desired category ID
$products_category_id = 4;
if(
isset( $_REQUEST[\'category_id\'][0] )
&& $products_category_id == $_REQUEST[\'category_id\'][0]
)
return \'some html styling\';
}
更新:尝试将此添加到结尾,但不起作用。。。
// change this to your desired category ID
$products_category_id = 4;................
if(
isset( $_REQUEST[\'category_id\'][0] )
&& $products_category_id == $_REQUEST[\'category_id\'][0]
)
return \'Some html styling\';
if ( $products_category_id = \'6\' ) {
return \'Some alternative html styling\';
} else {
return \'Some default html styling\';
}
}
还尝试按照下面建议的cpt线程编辑代码,但同样没有成功:(
add_filter( \'default_content\', \'wpa70073_default_products_content\' );
function wpa70073_default_products_content( $content ) {
switch($content->category){
// change this to your desired category ID
case\'4\':
$content=\'cat 4 content\';
break;
case\'6\':
$content=\'news content\';
break;
default:
$content=\'default content\';
break;
}
return $content;
}
最合适的回答,由SO网友:brasofilo 整理而成
您应该已链接到原始Q&;A从一开始
另一段来自@JanFabry的精彩代码,顺便说一句:)
Force category choice before creating new post?
完全使用他回答中提供的代码,这就是如何制作过滤器
default_content
工作:
add_filter( \'default_content\', \'wpse_71772_default_content\', 10, 2 );
function wpse_71772_default_content( $content, $post )
{
if( !isset( $_REQUEST[\'category_id\'] ) )
return $content;
switch( $_REQUEST[\'category_id\'][0] ){
// change this to your desired category ID
case\'1\':
$content=\'cat 4 content\';
break;
case\'3\':
$content=\'news content\';
break;
default:
$content=\'default content\';
break;
}
return $content;
}