我有出版物,我只想在永久链接中添加年份和月份。目前,发布年份和月份作为元值添加到帖子中。我已将出版物设置为自定义帖子类型,并为出版物的特定标题创建了分类法。我希望permalink是:
出版物/出版物名称/出版年份/出版月份/职务名称
我只想将发布年份和月份的元值添加到永久链接中。
到目前为止,我已经能够提取发布的年度和月份并将其添加到url,但不幸的是,当我尝试访问帖子时,我一直得到404。我想我在下面的步骤中走错了方向。。。
任何帮助都将不胜感激。
以下是我按照以下顺序执行的步骤:
由于我在url中添加了出版年份和出版月份,我读到我必须让WordPress知道这些自定义查询字符串变量。我添加了以下函数来注册这些自定义变量:
function pubyear_register_rewrite_tag() {
add_rewrite_tag( \'%pubyear%\', \'([0-9]{4})\');
}
add_action( \'init\', \'pubyear_register_rewrite_tag\');
function pubmonth_register_rewrite_tag() {
add_rewrite_tag( \'%pubmonth%\', \'([0-9]{2}\');
}
add_action( \'init\', \'pubmonth_register_rewrite_tag\');
向permalink结构中添加了年份和月份:
add_filter(\'post_type_link\', \'pub_term_permalink\', 10, 4);
function pub_term_permalink($permalink, $post, $leavename, $sample)
{
if ( false !== strpos( $permalink, \'%publication-title%/%pubyear%/%pubmonth%\' ) ) {
//get the publication-title
$publicationtype = get_the_terms( $post->ID, \'publication-type\' );
//get the year of the publication
$pubyear = date(\'Y\', get_post_meta($post->ID, \'pub_date\', true));
//get the month of the publication
$pubmonth = date(\'m\', get_post_meta($post->ID, \'pub_date\', true));
$rewritecode = array(
\'%publication-type%\',
\'%pubyear%\',
\'%pubmonth%\',
$leavename? \'\' : \'%postname%\',
);
$rewritereplace = array(
array_pop($publicationtype)->slug,
$pubyear,
$pubmonth,
$post->post_name
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
}
return $permalink;
}
3)添加重写规则:
function pub_add_rewrite_rules() {
add_rewrite_rule( \'^([^/]*)/([0-9]{4})/([0-9]{2})/([^/]+)?\', \'publications/index.php?pagename=$matches[3]\', \'top\' );
}
add_action( \'init\', \'pub_add_rewrite_rules\' );
4)确保已注册自定义帖子类型,并包括此重写数组:
\'rewrite\' => array
(
\'slug\' => \'publications/%publication-type%/%pubyear%/%pubmonth%\',
\'with_front\' => false
),