search
HomeBackend DevelopmentPHP Tutorial详解WordPress开发中的get_post与get_posts函数使用_PHP

get_post()
在一般主题制作时,get_post()函数我们一般很少会用到,但因为后面会讲到get_posts(),所以我们不得不先讲一下这个单数形式。这个函数的主要作用是,将一片指定的文章以一个对象或是数组的形式返回,以便我们后期利用。下面让我们简单的了解一下他的使用方法。

get_post()函数说明
WordPress 的函数名总是那么浅显易懂,get_post()函数正如其表,即获得一篇文章,将一篇指定的文章以一个对象或是数组的形式返回,以便我们后期利用。

函数使用

<&#63;php
 get_post($post_id, $output); 
&#63;>

$post_id变量,用于设置将要获取文章的ID,需要注意的是,这个变量我们不可以直接给一个实际值,那样会报错,我们只能以下面这样的形式调用。

$pid = 158;
get_post($pid);
//如果像get_post(158);这样调用则会报错

$post_id,默认值是none,经测试,这个变量不设置会报错,个人感觉这个变量好像没有默认值。

$output 变量用于设置返回数据的类型,有三种,对象、关联数组、数值数组。
对象:OBJECT
关联数组:ARRAY_A
数值数组:ARRAY_N
默认值:OBJECT

使用实例

<&#63;php
$mypost_id = 158;
$post_id_158 = get_post($mypost_id, ARRAY_A);
$title = $post_id_158['post_title'];
&#63;>

get_posts 
get_posts 函数,简单的来讲是 get_post 的复数新形势,但因为是文章多篇提取,所以使用方法上却略有不同,支持众多参数选择需要提取的文章,在 CMS 主题中经常被用到,当然如果你对 WordPress 有更深了解的话,你也有可能是用 WP_Query 来替代该函数,这就是后话了,今天主要介绍一下 get_posts 函数。

get_posts 函数详解
该函数属于 WordPress 的内置函数,用于在 WordPress 中提取多篇指定或随机文章。
越是描述简单的函数,使用起来就越是复杂,后面的需要仔细看咯!

使用方法

<&#63;php 
$args = array(
  'numberposts'   => 5,
  'offset'     => 0,
  'category'    => ,
  'orderby'     => 'post_date',
  'order'      => 'DESC',
  'include'     => ,
  'exclude'     => ,
  'meta_key'    => ,
  'meta_value'   => ,
  'post_type'    => 'post',
  'post_mime_type' => ,
  'post_parent'   => ,
  'post_status'   => 'publish' );
$posts_array = get_posts( $args ); 
&#63;>

$args是该函数必要的变量
get_posts( $args )将返回数组型的变量。

变量参数详解

<&#63;php 
$args = array(
  //需要提取的文章数
  'numberposts'   => 10,
 
  //以第几篇文章为起始位置
  'offset'     => 0,
 
  //分类的ID,多个用逗号将分类编号隔开,或传递编号数组,可指定多个分类编号。
  //大部分 CMS 使用该函数的重点。
  'category'    => ,
 
  //排序规则(注1)
  'orderby'     => 'post_date',
 
  //升序、降序 'ASC' —— 升序 (低到高) 'DESC' —— 降序 (高到底)
  'order'      => 'DESC',
 
  //要显示文章的ID
  'include'     => ,
 
  //要排除文章的ID
  'exclude'     => ,
 
  //自定义字段名称
  'meta_key'    => ,
  //自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。
  'meta_value'   => ,
 
  //post(日志)——默认,page(页面),
  //attachment(附件),any —— (所有)
  'post_type'    => 'post',
 
  //文章的 mime 类型
  'post_mime_type' => ,
 
  //要显示文章的父级 ID
  'post_parent'   => ,
 
  //文章状态
  'post_status'   => 'publish' );
&#63;>

注:

  • ‘author' —— 按作者数值编号排序
  • ‘category' —— 按类别数值编号排序
  • ‘content' —— 按内容排序
  • ‘date' —— 按创建日期排序
  • ‘ID' —— 按文章编号排序
  • ‘menu_order' —— 按菜单顺序排序。仅页面可用。
  • ‘mime_type' —— 按MIME类型排序。仅附件可用。
  • ‘modified' —— 按最后修改时间排序。
  • ‘name' —— 按存根排序。
  • ‘parent' —— 按父级ID排序
  • ‘password' —— 按密码排序
  • ‘rand' —— 任意排序结果
  • ‘status' —— 按状态排序
  • ‘title' —— 按标题排序
  • ‘type' —— 按类型排序

实例
刚我们讲到用数组去传参,当然我们也可以用字符串来给该函数传参,下面给一个简单的例子。

<&#63;php
$posts_rand = get_posts('numberposts=3&orderby=rand');
&#63;>

以上代码用于随机在 WordPress 中获取3篇文章。

总结
其实 query_posts() 和 get_posts() 函数,接受大部分的参数,使用同样结构的数据库查询语句,并能达到一样的目的,但部分主题作者提示 query_posts()有可能会扰乱 WordPress 主循环,所以在这里不推荐使用。
get_posts 使用不难,难在获取文章后怎样在页面中显示,这里就需要有一定的 PHP 知识了。
如果是在文章循环之外想要将查询内容显示出来,可以看一下setup_postdata这个函数,这个函数会给那些用惯了模板标签的童鞋很大的帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.