I am currently developing a WordPress theme based on _s because the project is pretty different than average WordPress projects.
I started a few days ago and have done designing and now I am stuck in one place for hours.
I am trying to create a function to generate video id from Youtube link (a custom field does the job for 'video' post type).
The output is something like this: a0uGWc170Jc.
The code I used is below:
$id = get_post_meta($post->ID, 'video_option_youtube-link', true);
$id = explode('?v=', $id);
if (empty($id[1])) {
$id = explode('/v/', $id);
}
$id = explode("&", $id[1]);
$id = $id[0];
echo $id;
This code works well only when I add it inside of WP Query. I tried to make a function and inserted this function to theme's function.php file and tried to echo inside WP_Query but it returns php error. The function I made is:
function my_videoid() {
$id = get_post_meta($post->ID, 'video_option_youtube-link', true);
$id = explode('?v=', $id);
if (empty($id[1])) {
$id = explode('/v/', $id);
}
$id = explode("&", $id[1]);
$id = $id[0];
return $id;
}
(also tried to echo instead of return)
So, what am I doing wrong?
I think you have missed the global $post, $wpdb;
Please try it.
Related
Hei everybody. Maybe someone could give me some tips , because I am stuck on this for second day.
function get_url_id() {
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_NUMBER_INT);
$data = $_GET['id'];
$final= xss_clean($data); // function to prevent xss, working
return $final;
}
function relax() {
;
}
function show_order_details_created_date() {
if( $user = wp_get_current_user() ){
$order_id= get_url_id();
if(!isset($order_id)) { relax(); } else {
$order = wc_get_order ($order_id);
$date=$order->get_date_created();
$date_mod=explode("T" , $date);
return $date_mod[0];
}
}
}
Wordpress is giving me critical error , that I can not even open to edit page section. If instead of $order_id I insert existing order number ITS WORKS ABSOLUTELY fine. If I print out variable it also shows ID without problem. Why I can not use variable here? Any hints, guys?
I want to get a URL which is coming from a React rout.
URL is like: http://localhost:3001/users/[member_username]
In which member_username will be dynamic as per the user name.
So for example if a url hit like http://localhost:3001/users/gray then a variable will get gray or url hit like http://localhost:3001/users/john then a variable will get john
Now i need to get that url into WordPress php file to create an API.
I have tried this solution but did not getting the exact solution that is fit to my problem.
Here is my API code that in which i need to get URL.
function get_user_id(){
$server_name = $_SERVER['SERVER_NAME'];
$user_name = basename("http://".$server_name."/users/admin");
// For now i have set the username as static, so it should be a dynamic as user hit the url.
$users = get_user_by('login', $user_name);
if( !empty($users) ){
foreach ($users as $key => $user) {
$user_name = new stdClass();
$user_name->id = $user->ID;
$user_name->user_login = $user->user_login;
$user_name->user_nicename = $user->user_nicename;
$user_name->user_email = $user->user_email;
return $user_name;
}
}
}
/*
*
* Add action endpoint building
*
*/
add_action( 'rest_api_init', function () {
register_rest_route( 'rest-endpoints/v1', '/userid', array(
'methods' => 'GET',
'callback' => 'get_user_id'
));
});
Could you let me know why that solution not fit for your problem?
seems is ok to get the username.
however, maybe you can try this
<?php
$url = parse_url('http://localhost:3001/users/yourname',PHP_URL_PATH);
$url = str_replace("/users/","",$url);
echo $url;
?>
You can use:
$url_path = parse_url('http://localhost:3001/users/a13/abc',PHP_URL_PATH);
$url = preg_replace("/\/(?:[^\/]*\/)*/","",$url_path);
echo $url;
output:
abc
demo: https://regex101.com/r/19x7ut/1/
or this regex:
\/(?:[^\/\s]*\/)*
demo: https://regex101.com/r/19x7ut/3/
both should work fine.
I've been working with Php for less than 2 months (this is also my first question so please tell me if I'm missing something) and it has been going smooth right up till today. I'm working on a form plugin for Wordpress and currently implementing the code to make the forms saved in the database to connect with a shortcode which includes the ID of the form in the database. The 1st form has an ID of 1 and the shortcode is IForm_1. Pretty simple.
The problem occurs when looping thru all the forms and not being able to pass the $ID value from the loop to the IForm function.
$ID= 0;
$FormID= 0;
settype($ID, "integer");
for ($x = 1; $x <= 300; $x++) {
global $ID;
$ID++;
$ShortCode = "IForm_";
$ShortCode .= $ID;
$FormID = $ID;
add_shortcode( $ShortCode, 'IForm_Array' );
$ShortCode ='';
}
here is the loop which is very simple, when the $ShortCode lines up with the shortcode used on the site it works and the IForm get used as it should.
function IForm(){
global $ID;
//testing_decode();
// Gets the value of baseTest from getDB and puts it in test.
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
}
Here is the function.
Problem is that $ID is always 300 in the function which is the end of the loop. IForm is executed when the $ID in the loop lines up with the shortcode ID on the site/post which tells me the $ID value is indeed correct for some part of the loop. When the ID is indeed correct I would like to pass it to the IForm function to use it to find the right form in the database(MySQL).
Now my question is how would I pass (if that can even be done) the $ID value on the 3rd row of the loop to the 5th row of function. Alternatively would be to force break the loop when it lines up and use the last $ID value to be passed to IForm.
WordPress makes this a little more complicated than it needs to be, because you can't pass additional parameters to a shortcode (afaik).
Before we start, let's understand the 300. The loop in which you add the shortcodes gets executed during an early stage of the page load. The actual call to your shortcode function at a later stage. At that time the global $ID variable will have its final value (300 in your case)
Here are two ways to solve this:
First, you can use closures, and inherit $ID from the parent scope:
for ($x = 1; $x <= 300; $x++) {
$ID++;
$ShortCode = "IForm_";
$ShortCode .= $ID;
$FormID = $ID;
add_shortcode( $ShortCode, function () use ($ID) {
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
} );
$ShortCode ='';
}
You can read more about it in the manual. It also explains the difference between use and global variables.
Second, you can use shortcode attributes. You would not use [Form_1] anymore, but [Form id=1]. Then you can access the id within the array that Wordpress automatically passes to your function.
function IForm($attr){
$ID = intval($attr['id']); // A little sanitation, because $attr could come from a user with low privileges
$DBForm = getDB($ID);
$Form = $DBForm;
$Form .= "Works but not really";
return $Form;
}
A little documentation about this is available here.
Lets see what you did there
$ID= 0;
// Define a variable called ID
for ($x = 1; $x <= 300; $x++) {
global $ID;
// get access to global variable id
$ID++;
// increment local or global counter, undefined behaviour
instead i recommend doing
global $ID;
for ($x = 1; $x <= 300; $x++) {
$ID++;
// Do what you think you have to do
do not pass variables over global variables into functions, instead use parameter
function IForm($id){
//testing_decode();
$DBForm = getDB($id);
$Form = $DBForm;
$Form .= "Works very good";
return $Form;
}
and call the function like
IForm(42); //or
IForm($ID);
i'm working on a simple plugin to count FB shares of post and
i want to create instance of the plugin class using a cron job.
the main part of the plugin is this:
class PostShareCount
{
public function __construct()
{
global $wpdb;
$this->db = $wpdb;
add_action('hourly_event', 'updateAllPostsShares');
add_shortcode('social-count', array($this, 'social_shares'));
}
public function updateAllPostsShares()
{
$this->db->query('CREATE TABLE IF NOT EXISTS wp_facebook_shares(
post_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
post_shares INT NOT NULL,
post_url VARCHAR(255) NOT NULL
)');
$posts = $this->db->get_results('SELECT ID, post_date, post_name FROM '.$this->db->posts.' WHERE ID < 3');
$fb_graph = 'http://graph.facebook.com/?id=';
$site = 'http://www.example.com/';
$posts_shares = [];
foreach ($posts as $post) {
$post_url = $site.$post->post_name;
$posts_shares[$post->ID] = array();
$posts_shares[$post->ID]['post_id'] = $post->ID;
$posts_shares[$post->ID]['post_url'] = $post_url;
$api_call = $fb_graph.$site.$post->post_name;
if (isset($this->get_response_body($api_call)->shares)) {
$posts_shares[$post->ID]['post_shares'] = $this->get_response_body($api_call)->shares;
} else {
$posts_shares[$post->ID]['post_shares'] = rand(80, 1200);
}
$this->db->replace('wp_facebook_shares', $posts_shares[$post->ID], array('%d', '%s', '%d'));
}
return $posts_shares;
}
}
and for a test to my cron i created this simple file:
<?php
require_once ('post-share-count.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>
but whenever i try to run it i get this error:
Call to undefined function add_action() in ..
any idea what is causing this and how can i fix it? thx
There is simpler way, how to test your cronjobs:
Install WP Crontrol plugin.
Now, you can run your crons from administration.
Go to WordPress Administration: Tools -> Cron Events
If your plugin is working properly, you should see your scheduled hook name here.
Click on Run Now
Calling function directly from PHP file
If you need for some reason to call plugin functions directly from testing PHP file, don't forget to include wp-load.php.
Example (file is in same directory as wp-load.php):
<?php
include ('wp-load.php');
$obj = new PostShareCount();
$obj->updateAllPostsShares();
?>
I have been having troubles for hours with this and it seems like it should be so simple.
I am making my first extension and want if a product is part of a category it does something. Its working fine in view.phtml but when I try and load it from my extension it doesnt work.
Originally I have been using:
<?php $yourCatIds = array(1,3);
$productCats = $_product->getAvailableInCategories();
But I know $_product wont work inside the extension and that I need to get the Model. I have tried:
<?php $yourCatIds = array(1,3,5,6);
$category = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$productCats = Mage::getModel('catalog/category')->load($cat_id);
if (count(array_intersect($yourCatIds,$productCats))) {}
else {
}
?>
And:
$product = Mage::getModel('catalog/product')->load($_item['product_id']);
$cats = $product->getCategoryIds();
And a few others I have seen on stackoverflow but nothing seems to be working. I dont get an error just dont get the same as when I do it in the phtml files.
Can anyone tell me where I am being silly?
UPDATE: THIS IS AS FAR AS I CAN GET BUT IT IS NOT WORKING
It prints "not working" :(
<?php
class Battery_Function_Helper_Data extends Mage_Core_Helper_Abstract
{
public function test(){
$yourCatIds = array(1,2,3,5,6,24);
$productCats = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
if (count(array_intersect($yourCatIds,$productCats))) {
echo 'Traveling on a Plane <img style="display: inline-block" src="http://www.somerset.lib.nj.us/images/help.gif"><br>';
}
else {
print("not working ");
}
}
}
?>
You can test the data step by step:
$category = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$productCats = Mage::getModel('catalog/category')->load($cat_id);
You can use dump($productCats), see is there some data. If is NULL, you should check the code. If there are some data ,then go the next step, show the data just like $productCats.