【问题标题】:Getting the post-id of another post by using meta-key in Wordpress在 Wordpress 中使用元键获取另一篇文章的 post-id
【发布时间】:2017-10-02 09:38:59
【问题描述】:

问题:如何使用 get_post_meta() 访问另一个帖子的帖子 ID?

你好,我目前在一个 Wordpress 网站上工作,在这个网站上我想从另一个帖子中访问 post-id,我打算使用 get_post_meta() 数组,但我不知道如何使用它。我不确定在哪里可以找到 $key 以及如何使用它?

这是我目前的代码...

帖子 1(我想“回显”帖子 ID 的帖子)。

<?php
     $educator_meta= get_post_meta(get_the_id(), 'educator_id');
?>
<html>
      <div class="container">
             <?php 
                  echo "This is the post-id of the educator post: ", $educator_meta[0];
                  echo "This is the current posts post-id: ", get_the_ID();
             ?>
       </div>
</html>

Post 2(我想从中获取 post-id 的页面)。

    <?php
$current_educator_id = get_the_id();
$course_lessons = new WP_Query( array(
    'post_type'     => 'educator',
    'order'           => 'asc',
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key'     => 'educator_id',
            'value'   => $current_educator_id,
            'compare' => 'IN',
        ),
    ),
) );?>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    如果您知道标题或 slug,您可以使用其他可能更简单的方法。

    $post = get_page_by_title( 'Your post title', OBJECT, 'post' );
    $post_id = $post->ID;
    

    如果你知道 URL,你也可以使用它:

    $url = "whatever-url-to-post-here";
    $postid = url_to_postid( $url );
    

    两者都会为您返回 ID - 第一种方法为您提供整个对象,因此您可以从中获取所有内容。

    通过 var_dump($post); 进行检查

    编辑:如果你真的想使用后元键,你可以通过这样做看到全部:

    highlight_string("<?php\n\$data =\n" . var_export(get_post_meta(get_the_id()), true) . ";\n?>");
    

    这将提供所有元键的易于阅读的概述。

    【讨论】:

      【解决方案2】:

      用户第三个参数
      $key_1_value = get_post_meta(get_the_ID(), 'key_1', true);
      因为它的默认值为false。

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 2018-06-11
        • 2021-10-17
        • 2020-10-11
        • 1970-01-01
        相关资源
        最近更新 更多