我正在使用AngularJS加载我的WordPress帖子列表,但是我无法使用任何PHP函数来处理我的partials文件。
我试过使用一些东西,比如search.php
而不是search.html
但这样做时,我会遇到一些错误,例如致命错误get\\u post\\u meta未定义。
现在我知道我们不应该把客户端和服务器端混为一谈,我可能会使用某种服务来解析我的PHP,但我不知道该怎么做。我需要我的search.php
为了呈现PHP标记,以便显示自定义字段,并使用其中的几个PHP函数。
最好的方法是什么?
在我的页面模板上(.php
) 我有--
<div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
© <?php echo date( \'Y\' ); ?>
</footer>
</div>
在我的PHP文件中,我想被调用到视图中,它有如下函数--
<?php
$pcomp1b = get_post_meta(get_the_ID(), \'pa_meta_comp1b\', true);
$pcomp1c = get_post_meta(get_the_ID(), \'pa_meta_comp1c\', true);
$pcomp1d = get_post_meta(get_the_ID(), \'pa_meta_comp1d\', true); ?>
数学--
if( is_numeric( $price1 ) ) {
$a1 = $price1;
}
$b1 = $pcomp1d;
$sqft1 = str_replace( \',\', \'\', $b1 );
if( is_numeric( $sqft1 ) ) {
$b1 = $sqft1;
}
$a2 = $pcomp2f;
$price2 = str_replace( \',\', \'\', $a2 );
if( is_numeric( $price2 ) ) {
$a2 = $price2;
}
$b2 = $pcomp2d;
$sqft2 = str_replace( \',\', \'\', $b2 );
if( is_numeric( $sqft2 ) ) {
$b2 = $sqft2;
}
$a3 = $pcomp3f;
$price3 = str_replace( \',\', \'\', $a3 );
if( is_numeric( $price3 ) ) {
$a3 = $price3;
}
$b3 = $pcomp3d;
$sqft3 = str_replace( \',\', \'\', $b3 );
if( is_numeric( $sqft3 ) ) {
$b3 = $sqft3;
}
$ppsqft1 = ROUND($price1 / $sqft1);
$ppsqft2 = ROUND($price2 / $sqft2);
$ppsqft3 = ROUND($price3 / $sqft3);
$ppsav = ROUND((($ppsqft1 + $ppsqft2 + $ppsqft3)/3));
$b4 = $property_area;
$parea = str_replace( \',\', \'\', $b4 );
if( is_numeric( $parea ) ) {
$b4 = $parea;
}
$ehvp = $ppsav * $parea;
$homevalue = number_format($ehvp, 0, \'.\', \',\');
echo \'$\' . $homevalue; ?>
和函数--
<?php if (class_exists(\'MRP_Multi_Rating_API\')){ MRP_Multi_Rating_API::display_rating_result(array(\'rating_item_ids\' => 2, \'show_count\' => false, \'result_type\' => \'value_rt\', \'no_rating_results_text\' => \'N/A\'));} ?>
那么我该如何处理这个问题呢
ng-view
还有我的分部模板?
UPDATE
这就是我当前的设置——首先,我有一个名为“搜索结果”的页面模板。php-
<?php
/* Template Name:Search Results */ ?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php $url_info = parse_url( home_url() ); echo trailingslashit( $url_info[\'path\'] ); ?>">
<title>Search</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="print" />
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.3.0.min.js"></script>
<?php wp_head(); ?>
</head>
<body>
<div id="page" ng-app="app">
<header>
<h1>
<a href="<?php echo home_url(); ?>">Search</a>
</h1>
</header>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div ng-Cloak ng-controller="MyController" class="my-controller">
<div ng-view></div></div>
<?php endwhile; ?>
<?php endif; ?>
<?php rewind_posts(); ?>
<div ng-controller="OtherController" class="other-controller">
<div class="text-center">
<dir-pagination-controls boundary-links="true" on-page-change="pageChangeHandler(newPageNumber)" template-url="/partials/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
<footer>
© <?php echo date( \'Y\' ); ?>
</footer>
</div>
<script>
function getdata($scope,$http){
$http.get("/wp-json/posts?type=property")
.success(function(data)
{$scope.result = data;}
);
}
</script>
<?php wp_footer(); ?>
</body>
</html>
然后我的应用程序脚本,而不将php文件作为部分调用--
var app = angular.module(\'app\', [\'ngRoute\', \'ngSanitize\', \'angularUtils.directives.dirPagination\'])
function MyController($scope) {
$scope.currentPage = 1;
$scope.pageSize = 2;
$scope.posts = [];
$scope.pageChangeHandler = function(num) {
console.log(\'search page changed to \' + num);
};
}
function OtherController($scope) {
$scope.pageChangeHandler = function(num) {
console.log(\'going to page \' + num);
};
}
app.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath(\'/partials/dirPagination.tpl.html\');
});
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when(\'/search-results\', {
templateUrl: myLocalized.partials + \'main.html\',
controller: \'Main\'
})
.when(\'/:ID\', {
templateUrl: myLocalized.partials + \'content.html\',
controller: \'Content\'
});
})
app.controller(\'Main\', function($scope, $http, $routeParams) {
$http.get(\'wp-json/posts?type=property\').success(function(res){
$scope.posts = res;
});
})
app.controller(\'Content\', function($scope, $http, $routeParams) {
$http.get(\'wp-json/posts?type=property/?filter["posts_per_page"]=25&filter["orderby"]=date&filter["order"]=desc/\' + $routeParams.ID).success(function(res){
$scope.post = res;
});
});
app.controller(\'MyController\', MyController);
app.controller(\'OtherController\', OtherController);
然后将搜索部分文件。php文件,其函数和代码如我的原始问题所示。
SO网友:jgraup
1)将URL重写为url rewrites. 它们易于设置、自定义,您可以访问所有WordPress。
在下面的课程中,你可以看到rewrites 已添加(您只需flush the rewrite rules 如果url的一部分匹配,则节可以用作动态变量(regEx->query_vars). 有趣的是,您可以随时终止请求以返回JSON数据,或者让WordPress除了指定template 要使用的页面。
因此,我们将转向前端请求:
example.com/api/angular/partial/custom
我们可以在内部使用:
example.com/index.php?__api_angular=1&partial=custom
注册
rewrite -- 但我认为这一点已经明确了。
这个类可以添加到任何地方(functions.php/plugins)。它实例化自己,并将需要的内容挂接到init()
. 就我个人而言,我喜欢使用类,因为代码是包含的,如果类是在其他地方定义的,则不会发生冲突。。。如果已经定义了类,它就不会重新创建该类。
<?php
if ( ! class_exists( \'AngularEndpoint\' ) ):
class AngularEndpoint {
const ENDPOINT_QUERY_NAME = \'api/angular\';
const ENDPOINT_QUERY_PARAM = \'__api_angular\';
// WordPress hooks
public function init() {
add_filter( \'query_vars\', array ( $this, \'add_query_vars\' ), 0 );
add_action( \'parse_request\', array ( $this, \'sniff_requests\' ), 0 );
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
// Add public query vars
public function add_query_vars( $vars ) {
// add all the things we know we\'ll use
$vars[] = static::ENDPOINT_QUERY_PARAM;
$vars[] = \'partial\';
$vars[] = \'filter\';
$vars[] = \'type\';
return $vars;
}
// Add API Endpoint
public function add_endpoint() {
add_rewrite_rule( \'^\' . static::ENDPOINT_QUERY_NAME . \'/partial/([^/]*)/?\', \'index.php?\' . static::ENDPOINT_QUERY_PARAM . \'=1&partial=$matches[1]\', \'top\' );
//////////////////////////////////
flush_rewrite_rules( false ); //// <---------- REMOVE THIS WHEN DONE
//////////////////////////////////
}
// Sniff Requests
public function sniff_requests( $wp_query ) {
global $wp;
if ( isset(
$wp->query_vars[ static::ENDPOINT_QUERY_PARAM ],
$wp->query_vars[ \'partial\' ] ) ) {
$this->handle_partial_request(); // handle it
}
}
// Handle Requests
protected function handle_partial_request() {
global $wp;
$partial_requested = $wp->query_vars[ \'partial\' ];
switch ( $partial_requested ) {
// example.com/api/angular/partial/ping
case \'ping\':
wp_send_json_success( array (
\'message\' => \'Enjoy your partial\', \'partial\' => $partial_requested,
) );
break;
// example.com/api/angular/partial/custom
case \'custom\':
add_filter( \'template_include\', function( $original_template ) {
return __DIR__ . \'/custom.php\';
} );
break;
// example.com/api/angular/partial/search
case \'search\':
add_filter( \'template_include\', function( $original_template ) {
return get_template_directory() . \'/search.php\';
} );
break;
default:
wp_send_json_error( array ( \'message\' => \'Invalid Request\' ) );
}
}
}
$wpAngularEndpoint = new AngularEndpoint();
$wpAngularEndpoint->init();
endif; // AngularEndpoint
custom.php例如,用作模板。com/api/角度/部分/自定义
<html>
<body>
<h1>Custom Stuff</h1>
<h2><?php echo "PHP Stuff" ?></h2>
<?php
$posts = get_posts();
?>
<ul>
<?php
foreach ( $posts as $post ) {
echo \'<li>\' . $post->post_title . \'</li>\' . PHP_EOL;
}
?>
</ul>
</body>
</html>
休息路线是另一个选项,因为您已经在使用
wp-json
, 就是定制
rest route. 这里需要的设置较少,这是一个优点。
<?php
if ( ! class_exists( \'AngularJSONEndpoint\' ) ):
class AngularJSONEndpoint {
const ENDPOINT_NAMESPACE = \'namespace/v2\';
/**
* Initialize WordPress hooks
*/
public function init() {
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
/**
* Add JSON API Endpoint
*/
public function add_endpoint() {
add_action(\'rest_api_init\', function () {
// http://example.com/wp-json/namespace/v2/angular?partial=custom
register_rest_route( static::ENDPOINT_NAMESPACE, \'/angular\', array (
\'methods\' => \'GET\',
\'callback\' => array($this, \'wp_json_namespace_v2__angular\'),
\'permission_callback\' => function (WP_REST_Request $request) {
return true;
}
));
});
flush_rewrite_rules(true); // FIXME: <------- DONT LEAVE ME HERE
}
/**
* Handle the endpoint
* @param $request
*
* @return WP_REST_Response
*/
function wp_json_namespace_v2__angular($request)
{
// json-api params
$parameters = $request->get_query_params();
// check for partial requests
if(isset($parameters[\'partial\'])){
switch($parameters[\'partial\']) {
case \'custom\':
require __DIR__ . \'/custom.php\';
die();
}
}
// return results
$data = array(
\'success\' => false,
\'message\' => \'Bad Request\'
);
return new WP_REST_Response($data, 400);
}
}
$wpAngularJSONEndpoint = new AngularJSONEndpoint();
$wpAngularJSONEndpoint->init();
endif; // AngularJSONEndpoint