Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在wordpress中添加自定义rest api支持时要编辑哪个文件_Php_Wordpress - Fatal编程技术网

Php 在wordpress中添加自定义rest api支持时要编辑哪个文件

Php 在wordpress中添加自定义rest api支持时要编辑哪个文件,php,wordpress,Php,Wordpress,我从未使用过php或wordpress,但正在尝试使用wordpress的自定义PostAPI 我找到了这个链接: 他们说我可以像下面这样添加类似的代码,它应该可以工作 add_action( 'init', 'my_book_cpt' ); function my_book_cpt() { $args = array( 'public' => true, 'show_in_rest' => true, 'label' => 'Books'

我从未使用过php或wordpress,但正在尝试使用wordpress的自定义PostAPI

我找到了这个链接:

他们说我可以像下面这样添加类似的代码,它应该可以工作

add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
  'public'       => true,
  'show_in_rest' => true,
  'label'        => 'Books'
);
register_post_type( 'book', $args );
}

但既然我是新手,我不知道该把它放在哪个文件里?有人知道吗?谢谢

Johan,您需要在functions.php中注册一个自定义的WP REST API路径,如下所示:

add_action('rest_api_init', 'yourPathName');

function yourPathName(){
    register_rest_route('nameItHere/version#', 'routNameHere', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'nameACallbackFunction',
    ));
}

function nameACallbackFunction($data) {
    $variablename = new WP_Query(array(
        'post_type' => 'name_of_your_post_type',
        'posts_per_page' => 5,
        's' => $data['term'],
        'orderby' => 'title',
        'order' => 'asc'
    ));

    $anotherVariable = array();

    while ($variableName->have_posts()) {
        $variableName->the_post();
        array_push($anotherVariable, array(
            'id' => get_the_ID(),
            'title' => get_the_title(),
            'content' => get_the_content()
        ));
    }

    return $anotherVariable;
}


然后,您可以使用
XMLHttpRequest()

在JS AJAX调用中引用新端点和其中的数据,具体取决于您的工作内容,此函数可以添加到您的子主题函数.php文件或插件php文件中。@gael感谢您的回答,这是什么意思,它取决于什么?我在wordpress网站上有一个自定义帖子,我想阅读并发布到其中,我得到了一个路径wp content/themes/projectname/functions.php,另一个路径wp includes/functions.php,例如,肯定在您的themes/projectname/functions.php中