是否可以使用 PHP 来比较两个 post,当标题匹配时,获取 post 的 ID?

Is it possible to use PHP to compare two posts and when the title matches, get the ID of the post?

首先了解一下上下文以了解我在做什么。我正在使用 WordPress。所以我有一个包含拉丁文文本列表的页面。这些项目(标题和摘录)自动 post 编辑在页面上(有点像博客页面),文本本身是 WordPress posts back-end。我有一个类别 "text" 和一个类别 "translation" 来分隔两类内容。

当我点击一个文本时,我会被转到一个可以阅读全文的详细信息页面。单击 link 时,post 的 ID 存储在 $GLOBALS 变量中。然后在详细信息页面上调用该变量以显示文本的全部内容。我使用 AJAX 调用来存储变量。这就是我 post 详细信息页面上的内容:

<div class="left">
 <?php
    $post_id = $GLOBALS['post_id'];
    $queried_post = get_post($post_id);
    $title = $queried_post->post_title;
    $content = $queried_post->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]&gt;', $content);
 ?>
 <h3><?php echo $title; ?></h3>
 <p><?php echo $content; ?></p>

我想做的是在第二列中显示同一详细信息页面上每个文本的翻译(css 没问题)。我尝试了一些这样的事情:

<div class="right">
 <?php
    $post_id_two = ???
    $queried_post = get_post($post_id_two);
$title_two = $queried_post->post_title;
    $content_two = $queried_post->post_content;
    $content_two = apply_filters('the_content', $content);
    $content_two = str_replace(']]>', ']]&gt;', $content);
 ?>
 <h3><?php echo $title_two; ?></h3>
 <p><?php echo $content_two; ?></p>

但我就是不知道如何将第二个 post 标题与第一个标题进行比较,并在相应的详细信息页面上显示正确的翻译。如果有更简单的方法,欢迎任何东西。

我认为更简单的方法可能是添加一个自定义元框,允许您将翻译文本的 post ID 作为元数据存储到 post 和拉丁文本.这是一种粗略的方法,但你至少会明白这个想法:

将此添加到您的主题或插件中的 functions.php。 (这类东西首选插件)

//Define the contents of your meta box
function prefix_meta_box_contents($post){
    $current_value = get_post_meta($post->ID, 'prefix_translation_post', true);
    ?>
    <input type="number" value="<?php echo $current_value; ?>" min="0" name="prefix_translation_post">
    <?php
}

//Save the meta data
add_action('save_post', 'prefix_save_translation_post_meta');
function prefix_save_translation_post_meta($post_id){
    if(array_key_exists('prefix_translation_post',$_POST)){
        update_post_meta( $post_id, 'prefix_translation_post', $_POST['prefix_translation_post'] );
    }
}

//Hook onto the add_meta_boxes action
add_action('add_meta_boxes','prefix_meta_box');
function prefix_meta_box(){
    //Register the box
    add_meta_box('prefix_translation_post_mb','Translation Post','prefix_meta_box_contents');
}

然后转到您的拉丁文本 post 并告诉它包含翻译的 post 的 ID 号。保存它,然后尝试将其用于您的翻译文本列:

<div class="right">
 <?php
    $post_id_two = get_post_meta($queried_post->ID, 'prefix_translation_post', true);
    $queried_post_two = get_post($post_id_two);
    $title_two = $queried_post_two->post_title;
    $content_two = $queried_post_two->post_content;
    $content_two = apply_filters('the_content', $content);
    $content_two = str_replace(']]>', ']]&gt;', $content);
 ?>
 <h3><?php echo $title_two; ?></h3>
 <p><?php echo $content_two; ?></p>