检查文章或页面是否存在WordPress函数get_page_by_title是为了以防重复建立,如果有多个标题相同的帖子,它将检查最老的发布日期,而不是最小的ID。因为这个函数使用MySQL‘=’比较,$page_title通常与默认排序规则不区分大小写。

get_page_by_title( string $page_title, string $output = OBJECT, string|array $post_type = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’page\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ )

 参数

$page_title

(string) (必须) 页面标题.

$output

(string) (可选) 所需的返回类型。对象之一,数组_A或数组_N,分别对应于WP_POST对象、关联数组或数字数组。

默认值:OBJECT

$post_type

(string|array) (可选) POST类型或POST类型数组。

默认值: ‘page’

返回值

存在返回WP_Post(或数组),不存在返回NULL。

函数原型

该函数位于wp-includes/post.php,在线地址:https://developer.wordpress.org/reference/files/wp-includes/post.php/

function get_page_by_title( $page_title, $output = OBJECT, $post_type = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’page\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ ) {

global $wpdb;

if ( is_array( $post_type ) ) {

$post_type = esc_sql( $post_type );

$post_type_in_string = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\” . implode( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’,\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”, $post_type ) . \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”;

$sql = $wpdb->prepare(

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”

SELECT ID

FROM $wpdb->posts

WHERE post_title = %s

AND post_type IN ($post_type_in_string)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”,

$page_title

);

} else {

$sql = $wpdb->prepare(

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”

SELECT ID

FROM $wpdb->posts

WHERE post_title = %s

AND post_type = %s

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”,

$page_title,

$post_type

);

}

$page = $wpdb->get_var( $sql );

if ( $page ) {

return get_post( $page, $output );

}

}

如何按标题查找WordPress页面ID,然后替换内容

在本例中,我们找到“SamplePage”的页面id,然后将页面的内容替换为“HelloWorld!”

function my_content($content) {

$page = get_page_by_title( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’Sample Page\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );

if ( is_page($page->ID) )

$content = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”Hello World!\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\”;

return $content;

}

add_filter(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’the_content\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’my_content\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’);

如何按标题查找WordPress自定义文章类型

这对于自定义POST类型很有用。以下是自定义类型“link”的$POST数组,标题为“立即实现世界和平”:

$mypost = get_page_by_title(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’World Peace Now\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, OBJECT, \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’link\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’);

print_r($mypost);

在wp_list_Pages中查找用于排除的页面ID

此示例将返回标题为“About”的页的$page对象。然后,在列出页面时,使用$page->id元素排除有关页。

<?php

$page = get_page_by_title( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’About\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ );

wp_list_pages( \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’exclude=\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’ . $page->ID );

?>

相关新闻

发表评论

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

联系我们

联系我们

151-1101-0018

在线咨询:
邮件:30115776@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部