wordpress获取自定义类型文章
时间 : 2023-12-18 12:45:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

在WordPress中,获取自定义类型的文章可以使用get_posts函数或者WP_Query类来实现。

方法1:使用get_posts函数

```php

$args = array(

'posts_per_page' => -1,

'post_type' => 'custom_type',

);

$custom_posts = get_posts($args);

foreach ($custom_posts as $post) {

setup_postdata($post);

// 输出文章标题

the_title();

// 输出文章内容

the_content();

// 输出其他文章信息

// ...

// 重置文章数据

wp_reset_postdata();

}

方法2:使用WP_Query类

```php

$args = array(

'posts_per_page' => -1,

'post_type' => 'custom_type',

);

$custom_query = new WP_Query($args);

if ($custom_query->have_posts()) {

while ($custom_query->have_posts()) {

$custom_query->the_post();

// 输出文章标题

the_title();

// 输出文章内容

the_content();

// 输出其他文章信息

// ...

}

// 重置文章数据

wp_reset_postdata();

}

请将上述代码片段中的'custom_type'替换为你想要获取的自定义文章类型的名称。然后,你可以根据需要输出文章的其他信息,比如文章标题、内容等。

以上就是使用WordPress获取自定义类型文章的方法。希望能对你有所帮助!

其他答案

在WordPress中,要获取自定义类型的文章,首先你需要创建一个自定义文章类型。你可以在主题的functions.php文件中或者使用插件来实现这一点。下面是一个简单的示例:

1. 在主题的functions.php文件中添加以下代码:

```php

// 自定义文章类型

function custom_post_type() {

$args = array(

'labels' => array(

'name' => '自定义文章',

'singular_name' => '自定义文章',

),

'public' => true,

'has_archive' => true,

'supports' => array('title', 'editor', 'thumbnail'),

);

register_post_type('custom_post', $args);

}

add_action('init', 'custom_post_type');

2. 保存并激活你的主题。现在,你可以在WordPress的后台看到一个名为“自定义文章”的菜单选项。

3. 创建自定义文章并发布它们。

4. 现在,你可以通过使用WP_Query或get_posts函数来获取自定义类型的文章。下面是一个使用WP_Query的示例:

```php

$args = array(

'post_type' => 'custom_post',

'posts_per_page' => 10, // 获取10篇文章

);

$query = new WP_Query($args);

if ($query->have_posts()) {

while ($query->have_posts()) {

$query->the_post();

// 在这里输出自定义类型文章的内容

the_title();

the_content();

}

} else {

// 未找到自定义类型文章

}

wp_reset_postdata();

这是一个基本的示例,你可以根据需要定制查询参数和显示内容。

希望这可以帮助你获取WordPress中的自定义类型文章。