当前位置:

WordPress 获取当前网页URL并自动跳转404页面

在很多的 WordPress 主题或者插件功能的开发中,我们总是需要获取到 WordPress程序给每个页面定义的 ID,不然也某些情况下是无法确定这是哪一个页面,针对于文章或者页面的 ID 获取基本可以使用 get_the_ID()这个函数来直接获取,但是在循环外该函数是无法获取到值的。

Wordpress 获取当前网页URL和网页ID

WordPress获取当前网页URL地址:


home_url(add_query_arg(array()));

但二级目录会出错,可用下面的代码来获取当前URL;


//放入FUNCTIONS 获取当前URL
function curPageURL() {
$pageURL = 'http://';
if ($_SERVER["HTTPS"] == "on") {
$pageURL= "https://";
}
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL = $pageURL.$_SERVER["SERVER_NAME"].
":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL = $pageURL.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}

<?php echo curPageURL();?>

通过URL获取文章页ID:


url_to_postid($current_url);

直接获取文章页ID:


global $post;
$id = $post -> ID;
echo $id;

通过ID获取网页链接地址:


get_permalink($pid);

通过URL获取分类页ID:


get_category_link( $category_id );

应用实例:通过ID获取URL,然后再判断URL里是否包含“?”,然后跳转404网页;


<?php
$current_url = home_url(add_query_arg(array()));
$pid = url_to_postid($current_url);
$link = get_permalink($pid);
if(strpos($current_url,'?') == false){
global $wp_query;
$wp_query->set_404();
status_header(404);
nocache_headers();
include( get_query_template( '404' ) );
die();
}
?>

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注