我目前正在为一个在Wordpress中使用Timber的网站开发。我正在使用不同站点的 API 从其他站点获取帖子,因此它们与该站点的当前状态保持同步。问题是我正在使用帖子标题字段从 API 获取正确的 ID。这意味着数据库中不会存储任何标题或内容数据。
有没有办法注册这些数据,以便 Timber PostQuery 对象也能正确获取这些页面?之后我无法访问或更改$result = new TimberPostQuery()
的结果,因为这些字段是受保护和私有的。
提前感谢!
绝对是一个边缘边缘情况。如果你能得到你需要的东西到WordPress ID,这些可以直接发送给PostQuery()
......
$result = new TimberPostQuery(array(2342, 2661, 2344, 6345,));
您可以尝试自己扩展PostQuery
类,看看这是否是可以包装在其中的自定义功能,以便您最终在顶层使用的 API 干净简单。
Timber 旨在根据您的使用案例进行扩展和定制。
您可以创建一个扩展TimberPost
的自定义类,并根据需要编写自己的方法来从 API 获取数据。
<?php
class CustomPost extends TimberPost {
/* not necessary, this just caches it */
private $myCustomContent;
/* override TimberPost::content */
public function content(){
/* if we've fetched it from the API this request, return the result */
if ( $this->myCustomContent ) return $myCustomContent;
/* otherwise fetch it, then return the result */
return $this->fetchCustomContent();
}
/* function to fetch from external API */
private function fetchCustomContent(){
/* whatever the API call is here.. */
$result = wp_remote_post....
/* maybe some error handling or defaults */
/* cache it on the object's property we setup earlier */
$this->myCustomContent = $result->content;
return $this->myCustomContent;
}
}
现在要使用我们的自定义类,我们有两个选择。我们可以手动决定何时使用它,将其指定为PostQuery()
中的第二个参数
<?php
/* Note: Passing in 'null' as the first argument timber uses the global / main WP_Query */
$items = new PostQuery( null, CustomPost::class );
/* This examples is a custom query (not the global / main query ) */
$args = [
'post-type' => 'my-custom-post-type',
// etc etc
];
$items = new PostQuery( $args, CustomPost::class );
/* Each Post in $items will be the class CustomPost instead of TimberPost */
如果您的自定义帖子类与特定的帖子类型相对应,则可以使用 Timber 类映射始终取回相应的自定义帖子类。
<?php
/* functions.php or similar */
add_filter( 'TimberPostClassMap', 'my_func_modify_class_map' );
function( $classMap ){
$classMap['my-custom-post-type'] = CustomPost::class;
return $classMap;
}
/* index.php or xxx.php template file... */
$args = [
'post-type' => 'my-custom-post-type',
// etc etc
];
/* No second argument needed */
$items = new PostQuery( $args );
/* Each Post in $items will be the class CustomPost instead of TimberPost */
希望这有帮助!