我正在开发 WordPress 主题并使用自定义字段我面临以下问题

问题描述

我的代码

#include <fstream>
#include <iostream>
#include <map>

int main(void) {

  std::fstream file;
  file.open("secret.txt",std::ios::in);
  std::map<int,std::string> map;

  std::string username;

  int count = 1;
  while (!file.eof()) {
    file >> username;
    try {
      std::stof(username);
    } catch (...) {
      std::cout << count << ". " << username << "\n";
      map.insert(std::make_pair(count,username));
      count++;
    }   
  }
  int choice;
  std::cout << "Choose your username: ";
  std::cin >> choice;

  username = map.at(choice);

  std::cout << "Your username is set to " << username;

  return 0;
}

代码应该给出:-

 <`li><img src="<?PHP echo get_post_meta($post->ID,'_for-gallery',true); ?> " alt=""></li>`

但是代码给出了这个:-

 <img src="Array" alt="" draggable="false">

解决方法

查看 get_post_meta() 的代码参考 - 如果第三个参数 ($single) 为 false,该函数将返回一个数组:

返回:(混合)一个数组,如果 $single 为假。元的价值 字段如果 $single 为真。错误的 $post_id 无效。

在您发送 true 的代码中,试试这个:

get_post_meta($post->ID,'_for-gallery',false);

更多信息在这里:https://developer.wordpress.org/reference/functions/get_post_meta/

,

当你使用 get_post_meta 函数时 $single 为 true 只获取第一个元素,但 false 获取所有元素以逗号分隔。

看你的代码,我想 custom_field 是一个 url,在这种情况下,为什么你需要一个数组作为 url?你必须得到一个字符串...

您可以在这里查看:https://developer.wordpress.org/reference/functions/get_post_meta/