在Timber PostQuery中注册获取的数据(不在数据库中)

时间:2019-04-19 15:30:48

标签: wordpress api twig timber

我目前正在开发一个在Wordpress中使用Timber的网站。我正在使用其他站点的API从其他站点获取帖子,因此它们与该站点的当前状态保持最新。问题是我正在使用帖子标题字段从API中获取正确的ID。这意味着数据库中没有存储标题或内容数据。

是否可以注册该数据,以便Timber PostQuery对象也可以正确获取这些页面?此后,我无法访问或更改$result = new Timber\PostQuery()的结果,因为这些字段是受保护的并且是私有的。

谢谢!

2 个答案:

答案 0 :(得分:1)

@Stan这绝对是一个边缘边缘边缘情况。如果您可以找到所需的WordPress ID,则可以直接将其发送到PostQuery() ...

$result = new Timber\PostQuery(array(2342, 2661, 2344, 6345,));

您可以尝试自己扩展PostQuery类,以查看是否可以将其包装在自定义功能中,以便最终在顶层使用的API简洁明了

答案 1 :(得分:0)

木材旨在针对您的用例进行扩展和定制。

您可以创建一个扩展了Timber\Post的自定义类,并根据需要编写自己的方法来从API提取数据。

<?php

class CustomPost extends \Timber\Post {

     /* not necessary, this just caches it */
     private $myCustomContent;

     /* override Timber\Post::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 Timber\Post */

如果您的自定义帖子类别与特定的帖子类型相对应,则可以使用Timber Class Map始终获取对应的“自定义帖子类别”。

<?php

/* functions.php or similar */
add_filter( 'Timber\PostClassMap', '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 Timber\Post */

希望这会有所帮助!