【问题标题】:How to remove meta value in all WordPress posts?如何删除所有 WordPress 帖子中的元值?
【发布时间】:2020-01-13 23:48:35
【问题描述】:

我正在写博客,我想添加一个作为特色帖子的横幅。

但我不确定如何只将一个帖子标记为“精选”,因此如果另一个帖子被标记为“精选”,它会将旧帖子从显示为精选中删除。

我尝试使用 ACF(高级自定义字段)复选框来标记精选帖子,但我的方法不正确。

这是我的代码。

<?php
global $post;

$myposts = get_posts( array(
    'posts_per_page'   => 1,
    'order'            => 'DESC',
    'numberposts'      => 1,
) );

if ( $myposts ) {
    foreach ( $myposts as $post ) : 
        setup_postdata( $post ); 
        if(get_field('featured_post')):
?>

一旦我标记了其他帖子的特色,什么都没有显示。

计划关注此approach,但我不知道如何删除旧的精选帖子。

【问题讨论】:

  • 使用 ACF 的更好方法是依靠内置的选项页面。为选项页面创建一个名为“精选帖子”或其他名称的字段。您可以将其设为下拉列表,以便只能选择一篇文章。

标签: wordpress


【解决方案1】:

ACF 复选框/True/False 字段是一个很好的起点。从那里开始的解决方案是......

  1. 挂钩acf/save_post 操作
  2. 检查当前保存的帖子是否启用了featured_post
  3. 如果启用,请取消设置以前精选帖子上的“精选”标志
  4. 如果启用,将帖子 ID 存储为特色帖子的全局选项 ('mysites_featured_post')
  5. 在呈现横幅时,从此选项获取精选帖子的 ID

对于该选项,您可以做两件事:使用 WP 自己的 update_option,或创建一个带有 Post 字段的 ACF 选项页面,该字段仅包含一个(精选)帖子。 ACF 选项页面的优点是您可以通过导航到选项页面在 wp-admin 中手动编辑精选帖子。

不过,我将使用 WP 的 update_option 来演示它:

function hookACFSavePost($post_id) {
  $marked_featured = get_field('featured_post', $post_id);
  if ($marked_featured) {
    // get previously featured post
    $prev_featured_post = get_option('mysites_featured_post', false);
    if (is_numeric($prev_featured_post)) {
      // disable featured flag on the previously featured post, for consistency:
      update_field('featured_post', false, $prev_featured_post);
    }
    // store this as the current featured post
    update_option('mysites_featured_post', $post_id, true);
  }
}
add_action('acf/save_post', 'hookACFSavePost', 20);

通过这种方式,我们实现了禁用先前选择的帖子(如果存在)上的“精选”复选框,并将新精选帖子的 ID 存储在“mysites_featured_post”选项中。

然后要获得用于呈现横幅的精选帖子,您可以从选项中检索$post_id

$featured_post_id = get_option('mysites_featured_post', false);
if ($featured_post_id) {
  $post = get_post( $featured_post_id );
  // render the post('s ID)
  // ...
}

这个解决方案简单而高效,因为它不必遍历/查询所有帖子的元条目来查找当前精选帖子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2014-04-08
    • 2019-09-28
    • 2021-07-09
    • 1970-01-01
    相关资源
    最近更新 更多