wordpress根据页面别名获取页面数据的方法

 
更多

最近用wordpress做了一个外包项目,记录一下自己写的一个通过页面别名获取页面数据的方法,代码如下:

/**
 * 根据别名检索内容
 *  
 * @global wpdb $ wpdb WordPress数据库抽象对象。
 *  
 * @param string|array $page_slug 页面别名
 * @param string $output 可选。 所需的返回类型。 OBJECT,ARRAY_A或ARRAY_N之一,对应于
 * 分别是WP_Post对象,关联数组或数字数组。 默认OBJECT。
 * @param string|array $post_type 可选。 帖子类型或帖子类型数组。 默认“页面”。
 *
 * @return WP_Post|array|null 成功时为WP_Post(或数组),失败时为null。
 */
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page') {
    global $wpdb;

    $op_symbol_slug = $op_symbol_type = '=';

    if (is_array($page_slug)) {
        $page_slug = esc_sql($page_slug);
        $page_slug = '(' . implode("','", $page_slug) . ')';
        $op_symbol_slug = 'IN';
    }

    if (is_array($post_type)) {
        $post_type = esc_sql($post_type);
        $post_type = '(' . implode("','", $post_type) . ')';
        $op_symbol_type = 'IN';
    }

    $id = $wpdb->get_var(sprintf(
        'SELECT ID FROM %s WHERE post_name %s %s AND post_type % %',
        $op_symbol_slug,
        $page_slug,
        $op_symbol_type,
        $post_type
    ));

    return $id ? get_post($id, $output) : null;
}

将该函数拷贝到 /wp-includes/post.php 文件中去,即可全站使用。

打赏

本文固定链接: https://www.cxy163.net/archives/3358 | 绝缘体

该日志由 绝缘体.. 于 2019年07月17日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: wordpress根据页面别名获取页面数据的方法 | 绝缘体
关键字: , , , ,

wordpress根据页面别名获取页面数据的方法:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter