PHP code in WordPress page template doesn't ex

2019-08-16 20:27发布

问题:

Can anyone tell me why this code in a wordpress 'page template' doesn't execute?

'Echo' seem to work but all 'include' and 'print_r()' and other functions don't. This exact code works on my home server but not on wordpress hosted site:

<?php

/**
 * Template Name: fbshares
 *
 * A custom page template for displaying all posts.
 *
 * The "Template Name:" bit above allows this to be selectable
 * from a dropdown menu on the edit page screen.
 *
 * @package WordPress
 * @subpackage Twenty_Ten
 * @since Twenty Ten 1.0
 */

get_header(); ?>

<div id="container">
<div id="content" role="main" class="fullpagejoel">

 <?php 
    echo "x";
    $url = "http://www.google.com";

    $social = array(
        'twitter' => 'http://cdn.api.twitter.com/1/urls/count.json?url=',
        'facebook' => 'https://graph.facebook.com/',
        'stumbleupon' => 'http://www.stumbleupon.com/services/1.01/badge.getinfo?url='
    );

    $json = file_get_contents($social['twitter'].$url, false);
    $a = json_decode($json, true);
    $r['twitter'] = $a['count'];

    print_r($a);
    echo count($a).' [OK]';

 ?>

回答1:

Don't have enough rep to comment, but have you checked the source? WordPress dies silently, but often there is something in the source.

Short answer though, yes, you can execute any php you want in a template. I just copy pasted it into a WordPress template on our test server and it ran fine.



回答2:

I just found the problem. After debugging every bit item by item, the problem is that WordPress doesn't allow you to run file_get_contents, instead you have to use wp_remote_get like this:

GOOD: $json = wp_remote_get( $social['twitter'].$url );
BAD: $json = file_get_contents($social['twitter'].$url, false);

I just wasted a full day on this so I hope it helps someone else.



标签: php wordpress