I am trying to access php variable from wordpress shortcode function and use into og filter.
I have tried with php superglobals, set transient also, but nothing give the needed result.
Can someone take a look and help, thanks!
That's my code:
add_shortcode('test', 'get_sheet_value_shortcode');
function get_sheet_value_shortcode() {
ob_start();
$API = get_option('google_sheet_api');
$google_spreadsheet_ID = get_option('google_sheet_id');
$LANG = get_language_shortcode();
$api_key = esc_attr( $API);
$get_cell = new WP_Http();
$cell_url = "https://sheets.googleapis.com/v4/spreadsheets/$google_spreadsheet_ID/values/$LANG!A1:Z1000/?majorDimension=ROWS&key=$api_key";
$cell_response = $get_cell -> get( $cell_url);
if ( empty( $cell_response) ) {
return;
}
$json_body = json_decode($cell_response['body'],true);
$values = $json_body['values'];
//$values = json_encode($values);
array_shift($values); // removes first column key
if (! empty($values) ) {
$count = count($values);
// this will be using for share f-nality, so we can get same quote
$quote_number = array_search($rand_values, $values);
$rand_values = $values[array_rand($values)];
$image = (! empty($rand_values[3]) ) ? $rand_values[3] : '';
$GLOBALS['ogimage'] = $image;
}
ob_get_clean();
}
add_filter( 'aioseo_facebook_tags2', 'aioseo_filter_facebook_title2', 99 );
function aioseo_filter_facebook_title2( $facebookMeta ) {
$image = $GLOBALS['ogimage'];
if ( is_page('test') ) {
$facebookMeta['og:image'] = $image;
}
return $facebookMeta;
}
Related
I have a PHP array being created from a list of options in a WordPress plugin ($checklist) and I need to add some HTML to it.
public function get_the_checklist() {
// The default list
$options = get_option('uc_settings');
if (isset($options['list'])) {
$checklist = $options['list'];
// Split the list by line break
$checklist = preg_split('/[\n\r]+/', ($options['list']));
// Convert to associative array
foreach($checklist as $item) {
$item = '<div>'.$item.'</div>';
$default_checklist[] = array(
'text' => $item
);
}
}
// Are we resetting to default?
$reset = isset($_GET['reset_list']) ? true : false;
if ($reset) {
$user_id = get_current_user_id();
update_user_meta($user_id, 'user_checklist', $default_checklist);
return $default_checklist;
}
// Is user logged in?
if (is_user_logged_in()) {
$user_id = get_current_user_id();
// Look for custom list
$user_checklist = get_user_meta($user_id, 'user_checklist', true);
if (!$user_checklist) {
$user_checklist = $default_checklist;
}
} else {
return $default_checklist;
}
return $user_checklist;
}
I have done the following and it does add the prefix and suffix but it is showing as text and not HTML.
foreach($checklist as $item) {
$item = '<div>'.$item.'</div>';
$default_checklist[] = array(
'text' => $item
);
}
Here is an example of the output of the PHP above:
How can I make the text output as HTML instead?
there is two parameters to return Object as JSON
I try to get Posts By Id And attach to Array :
// Get Considered Posts, Training, Service, Intall
public function get_considered_posts() {
$item = new stdclass();
$item->msg = 'Empty';
$item->status = false;
$result = Array();
$post = $get_post_by_id( 156 ); // Training
if ( $post ) {
$result[] = $post ;
}
$post = $get_post_by_id( 164 ); // Service
if ( $post ) {
$result[] = $post ;
}
$post = $get_post_by_id( 161 ); // Intall
if ( $post ) {
$result[] = $post ;
}
if (count( $result ) == 0 ) {
$item->msg = 'Empty';
$item->status = false;
} else {
$item->msg = 'Success';
$item->status = true;
}
$item->result = $result;
return $item;
}
Here I want to use Only 5 Properties of Every Post :
// Get Post By Id
private function get_post_by_id( $pid ) {
$post = get_post( $pid = 0 );
if ( $post ) {
if ($post->post_status == 'publish') {
$object = new stdclass();
$object->id = $post->ID;
$object->cid = $pid;
$object->title = $post->post_title;
$object->content = $post->post_content;
$object->image = ''.wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
return $object;
}
}
return $post;
}
But it shows 500 Internal Server Error
When I check error_log it show :
[17-May-2016 14:27:54 UTC] PHP Notice: Undefined variable: get_post_by_id in /home/codypars/public_html/app/wp-webservice/helper.php on line 62
[17-May-2016 14:27:54 UTC] PHP Fatal error: Function name must be a string in /home/codypars/public_html/app/wp-webservice/helper.php on line 62
How I can fix it ?
Solved: thank you CD-jS And JustOnUnderMillions. To call own functions inside PHP class the right syntax is :
this->myFunctionName( $Param1, $Param2, $Param3, ...);
Remove the $ from the front of your function names when you're calling them.
e.g.
$post = $get_post_by_id( 164 );
Should be
$post = get_post_by_id( 164 );
<?php
define('PATH', dirname(dirname(__FILE__)).'/');
require_once (PATH.'./wp-blog-header.php');
global $wpdb;
// if(!isset($_POST['username'])){
// //echo $_POST['submit'];
// exit('非法访问!');
// }
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$checkcode = $_POST["checkcode"];
$query_pwd_str = "SELECT password FROM yjhy_users_custom WHERE username=%s";
if($wpdb == null)
echo "wpdb is null";
$pwd_query_result = $wpdb->get_results($wpdb->prepare($query_pwd_str, $username));
$pwd_query_result_count = count($pwd_query_result);
if($pwd_query_result_count == 1){
//已经存在该用户名,返回数据
// error here
header('Content-type:text/json');
$json_ouput = '{"status":"success","errormsg":"'.$username.'"}';
echo $json_ouput;
}
?>
With the code above, I use method post to refer to the php file, and it ALWAYS responsed with 404 Error.
But, when I modify PHP code as BELOW:
<?php
//****************** move the function header() here
header('Content-type:text/json');
//****************** echo "{" here
echo "{";
?>
<?php
define('PATH', dirname(dirname(__FILE__)).'/');
require_once (PATH.'./wp-blog-header.php');
global $wpdb;
// if(!isset($_POST['username'])){
// //echo $_POST['submit'];
// exit('非法访问!');
// }
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$checkcode = $_POST["checkcode"];
$query_pwd_str = "SELECT password FROM yjhy_users_custom WHERE username=%s";
if($wpdb == null)
echo "wpdb is null";
$pwd_query_result = $wpdb->get_results($wpdb->prepare($query_pwd_str, $username));
$pwd_query_result_count = count($pwd_query_result);
if($pwd_query_result_count == 1){
//已经存在该用户名,返回数据
// error here
$json_ouput = '"status":"success","errormsg":"'.$username.'"';
echo $json_ouput;
}
?>
<?php
//****************** echo "}" here
echo "}";
?>
AND THEN, it works, the server response status is 200!
I'm puzzled about this problem, and have searched all day and can't find the answer!
Why does the code work like this?
With 1 days' time, I find it out!
I request the link with the file path http://localhost:7770/api/register.php directly rather than request link by creating a page in the Dashboard, so the link is not in the WP's database.
And WP framework need to initialize itself when execute wp(); in the require_once (PATH.'./wp-blog-header.php');, but when the initial action execute in the file /wp-includes/class-wp.php with code below:
public function main($query_args = '') {
$this->init();
**$this->parse_request($query_args);**
$this->send_headers();
$this->query_posts();
$this->handle_404();
$this->register_globals();
do_action_ref_array( 'wp', array( &$this ) );
}
}
the statement $this->query_posts(); need to check the link $this->parse_request();. the func parse_request():
public function parse_request($extra_query_vars = '') {
global $wp_rewrite;
/**
* Filter whether to parse the request.
*
* #since 3.5.0
*
* #param bool $bool Whether or not to parse the request. Default true.
* #param WP $this Current WordPress environment instance.
* #param array|string $extra_query_vars Extra passed query variables.
*/
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
return;
$this->query_vars = array();
$post_type_query_vars = array();
if ( is_array( $extra_query_vars ) ) {
$this->extra_query_vars = & $extra_query_vars;
} elseif ( ! empty( $extra_query_vars ) ) {
parse_str( $extra_query_vars, $this->extra_query_vars );
}
// Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
// Fetch the rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
if ( ! empty($rewrite) ) {
// If we match a rewrite rule, this will be cleared.
***$error = '404';***
$this->did_permalink = true;
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
list( $pathinfo ) = explode( '?', $pathinfo );
$pathinfo = str_replace( "%", "%25", $pathinfo );
list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$self = $_SERVER['PHP_SELF'];
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
And the link is not in the database, so WP set the error 404 here below:
And then I get the error 404in ***$error = '404';***!
resolve solution:
create a page in the Dashboard.
modify the page url you want.
put your code in the page template.
use this template in the page.
and Ok
i using a wordpress plugin, i notice that returns a error on
$alias = (string)end(array_keys($settings));
above line .the error is
PHP Strict Standards: Only variables should be passed by reference in on wordpress function
i added that function below. anyone know how to solve that error please, becoz admin dashboard of the plugin not loading because of this error.
/*
* GET modules lists
*/
function load_modules ()
{
$folder_path = $this->cfg['paths']['plugin_dir_path'] . 'modules/';
$cfgFileName = 'config.php';
// static usage, modules menu order
$menu_order = array();
foreach(glob($folder_path . '*/' . $cfgFileName) as $module_config ){
$module_folder = str_replace($cfgFileName, '', $module_config);
// Turn on output buffering
ob_start();
if( is_file( $module_config ) ) {
require_once( $module_config );
}
$settings = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer
if(trim($settings) != "") {
$settings = json_decode($settings, true);
$alias = (string) end(array_keys($settings));
// create the module folder URI
// fix for windows server
$module_folder = str_replace( DIRECTORY_SEPARATOR, '/', $module_folder );
$__tmpUrlSplit = explode("/", $module_folder);
$__tmpUrl = '';
$nrChunk = count($__tmpUrlSplit);
if($nrChunk > 0) {
foreach ($__tmpUrlSplit as $key => $value){
if( $key > ( $nrChunk - 4) && trim($value) != ""){
$__tmpUrl .= $value . "/";
}
}
}
// get the module status. Check if it's activate or not
$status = false;
// default activate all core modules
if(in_array( $alias, $this->cfg['core-modules'] )) {
$status = true;
}else{
// activate the modules from DB status
$db_alias = $this->alias . '_module_' . $alias;
if(get_option($db_alias) == 'true'){
$status = true;
}
}
// push to modules array
$this->cfg['modules'][$alias] = array_merge(array(
'folder_path' => $module_folder,
'folder_uri' => $this->cfg['paths']['plugin_dir_url'] . $__tmpUrl,
'db_alias' => $this->alias . '_' . $alias,
'status' => $status
), $settings );
// add to menu order arrayhttp://cc.aa-team.com/wp-plugins/smart-seo-v2/wp-admin/admin-ajax.php?action=pspLoadSection§ion=Social_Stats
if(!isset($this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']])){
$this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']] = $alias;
}else{
// add the menu to next free key
$this->cfg['menu_order'][] = $alias;
}
// add module to activate modules array
if($status == true){
$this->cfg['activate_modules'][$alias] = true;
}
// load the init of current loop module
if( $status == true && isset( $settings[$alias]['module_init'] ) ){
if( is_file($module_folder . $settings[$alias]['module_init']) ){
//if( is_admin() ) {
$current_module = array($alias => $this->cfg['modules'][$alias]);
require_once( $module_folder . $settings[$alias]['module_init'] );
//}
}
}
}
}
// order menu_order ascendent
ksort($this->cfg['menu_order']);
}
End rereceives value by reference, but result of function is not variable.
You could rewrite your code.
$array_keys = array_keys($settings);
$alias = (string)end($array_keys);
unset($array_keys);
Can someone help why my JSON file can't show? I beginner for JSON. This is my code, its only show blank document. I am learning this tutorial from this website http://contohprogramandroid.blogspot.com/2013/10/contoh-program-android-aplikasi-wisata.html. thank you so much.
this my image when running the code.
//this is the code webservice.php
<?php
class Database {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "wisata_jogja";
private $conn;
// constructor
function __construct() {
try{
$this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass );
}catch( PDOException $e ) {
echo "error pdo $e";
}
}
public function showAllData( $table ) {
$sql ="SELECT * FROM $table";
$q = $this->conn->query( $sql ) or die( "Failed !!" );
while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {
$data[] = $r;
}
return $data;
}
}
$database = new Database();
$response = array();
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
$response['location'] = array();
foreach ( $database->showAllData( 'lokasi' ) as $value ) {
$kode = array();
extract( $value );
$kode['id'] = $id;
$kode['nama'] = $nama;
$kode['alamat'] = $alamat;
$kode['gambar'] = $gambar;
$kode['lat'] = $lat;
$kode['lng'] = $lng;
array_push( $response['location'], $kode );
}
echo json_encode( $response );
}
?>
Your condition to output is this:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
Thus, the script won't output any JSON since condition is not met.
From your screenshot it is clear your are missing the GET parameters.
In your browser add the parameter to the url:
http://localhost/wisata/webservice.php?get=lokasi
It's always good to take alternative action when condition is not true.
You should always echo something just so you know what is going on:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
//..............
echo json_encode( $response );
}else{
echo "cannot output JSON data: parameter is missing!!;
}
Are you sure that you pass the GET variable "lokasi" to your script ?
Otherwise, it would not go through the if condition
if(isset($_GET['get'] ) && $_GET['get']=='lokasi')
You can check this by trying to dump the variable or any foobar data inside the if condition to verify your code goes that far, for instance :
if(isset($_GET['get'] ) && $_GET['get']=='lokasi') {
$response['location'] = array();
$myTest = array('test');
var_dump($myTest); // Should display something on screen
// The rest of your code here