PHP - How to use functions from another directory file? - php

I have this function in $root/content/plugins/musicplayer/includes/player.php
public function head_script( $id, $playlist_id, $songs, $in_popup, $autoplay = false ) {
$output = '';
$playlist = '';
$artist = '';
$free = null;
$external = 0;
if ( $songs ) {
$ogg = '';
foreach ( $songs as $song ) {
$free = $song->free;
if ( $song->poster ) {
$poster = esc_url( $song->poster );
} else {
$poster = $this->get_default_playlist_poster( $playlist_id );
}
$playlist .= '{ title : "' . $song->name . '", mp3:"'. esc_url( $song->mp3 ) .'"';
if ( $song->artist )
$playlist .= ', artist : "' . $song->artist . '" ';
if ( $free != 'on' ) {
$playlist .= ',poster : "' . $poster . '" ';
$playlist .= ' },';
}
$playlist = substr( $playlist, 0, -1 );
$output .= '<script type="text/javascript">//<![CDATA[';
$output .= "\n";
$output .= 'jQuery(document).ready(function($) {
new jPlayerPlaylist( {
jPlayer: "#jquery_jplayer_' . $id . '",
cssSelectorAncestor: "#jp_container_' . $id . '" },
['.$playlist.'], {
swfPath: "' . WOLF_JPLAYER_PLUGIN_URL . '/assets/js/src",
wmode: "window", ';
$output .= '});'; // end playlist
if ( ! $in_popup )
$output .= $this->popup();
$output .= '});'; // end document ready playlist
$output .= '//]]></script>';
}
echo $output;
}
How can I use it in $root/content/themes/bigwolf/index.php, with it still being able to call all the functions that are originally and normally called in the native directory, without any problem?

You can include it. That's how you do it.
f1.php
<?php
function func1()
{
echo 'hi';
}
f2.php
<?php
require_once('f1.php'); // require
//include 'f1.php'; // or include
func1();

Obviously musicplayer is a plugin. If it's properly formatted, WordPress will automatically include it. So in the main file of your plugin put
require_once __DIR__ . "/includes/player.php';
That will bring your player.php in and give you access to the functions in it.
HTH,
=C=

Related

Custom Flash message PHP

This flash message helper is from traversymvc: a custom open-source php mvc.
My question is: is it necessary to check if ($_SESSION[$name]) is not empty on line 6(3rd if) when we've already made sure that it is not empty from the if condition before it.
Thanks.
<?php
session_start();
function flash($name = '', $message = '', $class = 'alert alert-success') {
if (!empty($name)) {
if (!empty($message) && empty($_SESSION[$name])) {
if (!empty($_SESSION[$name])) {
unset($_SESSION[$name]);
}
if (!empty($_SESSION[$name . '_class'])) {
unset($_SESSION[$name . '_class']);
}
$_SESSION[$name] = $message;
$_SESSION[$name . '_class'] = $class;
} elseif (empty($message) && !empty($_SESSION[$name])) {
$class = !empty($_SESSION[$name . '_class']) ? $_SESSION[$name . '_class'] : '';
echo '<div class= "' . $class . '" id="msg-flash">' . $_SESSION[$name] . '</div>';
unset($_SESSION[$name]);
unset($_SESSION[$name . '_class']);
}
}
}

Load More Button With PHP DirectoryIterator?

I have a number of "image gallery" style pages within my WordPress site. I'm trying to find out whether or not it's possible, using the method that I'm using, to create a 'Load More' button so that only 15 (for example, can be whatever) thumbnails load at a time.
To gather the files that should be displayed I'm using PHP's DirectoryIterator. I use the same custom function for every page, but the function itself is a bit long and messy. Essentially, I need to be able to just drop files into the appropriate directory and have them automatically detected and have the thumbnail shown with a link to the full-size image.
I already have this set up and working. Half of the function also checks for any sub-directories and repeats the process for those so that I can have any number of "galleries", each with any number of images, on a single page simply by creating directories and uploading files.
It's rather long, but for reference I feel like I need to paste the full function when asking this question so that people know what I'm working with. The type of content I'm working with is video game screenshots.
function display_screenshots() {
global $post;
$post_data = get_post($post->post_parent);
$parent_slug = $post_data->post_name;
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/';
if(is_dir($img_list_directory)) {
$found_shots = array();
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
if(is_dir($img_list_directory)) {
foreach(new DirectoryIterator($img_list_directory) as $dir) {
if($dir->isDir() && $dir != '.' && $dir != '..' && $dir != 'thumb') {
$dir_h2 = substr($post->post_title, 0, -12) . ' - ' . str_replace(array('Hd ', ' Hd ', ' Of ', ' The ', ' A ', ' To '), array('HD ', ' HD ', ' of ', ' the ', ' a ', ' to '), ucwords(str_replace("-", " ", $dir))) . ' Screenshots';
$img_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$thumb_directory = '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/thumb/';
$img_list_directory = getcwd() . '/wp-content/uploads/screenshots/' . $parent_slug . '/' . $dir . '/';
$found_shots = array();
echo '<hr />';
echo '<h2>' . $dir_h2 . '</h2>';
echo '<div class="screenshot-thumbs-outer">';
echo '<div class="screenshot-thumbs-inner">';
foreach(new DirectoryIterator($img_list_directory) as $file) {
if ($file->isDot()) continue;
$fileName = $file->getFilename();
$filetypes = array(
"png",
"PNG"
);
$filetype = pathinfo($file, PATHINFO_EXTENSION);
if (in_array(strtolower($filetype), $filetypes )) {
$found_shots[] = array(
"fileName" => $fileName
);
}
}
asort($found_shots);
foreach($found_shots as $file) {
$filename = $file['fileName'];
$thumbname = substr($filename, 0, -3).'jpg';
echo '<a href="#" data-featherlight="'.$img_directory.$filename.'" rel="nofollow">';
echo '<img src="'.$thumb_directory.$thumbname.'"/>';
echo '</a>';
}
echo '</div>';
echo '</div>';
}
}
}
}
Again, this function is working as intended, I just want to find some way to add 'Load More' functionality so that if there are 150 images, only 15 will load at a time. I'll also need to duplicate the code for the 'Load More' button in the second half of the function so that it's happening for any additional galleries on the page as well.
I realize that this is a lot for someone else to dive into, but I've put a lot of time into combing answers on this site as well as searching Google and I haven't been able to find a solution that's really relevant to the function I'm using to gather/display these images.
Any help will definitely be appreciated.
Thanks!

Using TwitterOauth within a function

I am trying to create a small php script that pulls down a list of all user id's of people that are following/friends with a handle on twitter, for this I am using https://twitteroauth.com
I can get the id's to a file itself when I use either "friends" or "followers" individually, but when I am trying to move this script to a function I get "Fatal error: Call to a member function get() on null" (line 19)
the error is triggered because this line
" $tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
"
is being used inside a function...
I used composer and tried and got it to work outside a function.. the 2 main files are
index.php
#!/usr/bin/php
<?php
require __DIR__ . '/vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once 'config.php';
// Pass in arguments
if (PHP_SAPI === 'cli') {
$type = $argv[1];
$term = $argv[2];
}
else {
$type = $_GET['type'];
$term = $_GET['term'];
}
switch ($type){
case 'timeline':
include 'timeline.php';
break;
case 'followers':
case 'friends':
include 'f.php';
break;
case 'ratelimit':
include 'ratelimit.php';
break;
case 'users_followers':
case 'users_friends':
include 'users.php';
break;
case 'all':
// include 'timeline.php';
include 'f.php';
break;
}
?>
And f.php
<?php
function getFrindsFollowers($term, $type){
// create file to print follwer/friends id's to file
$file = "files/" . $term . '_' . $type . '.csv';
// set empty content to file
$content = null;
// set previous cursor
$previous_cursor = 0;
$next_cursor = -1;
$loop_num = 0;
// While statment for followers or friends calls.
while($next_cursor != $previous_cursor && $loop_num < 15 && $next_cursor != 0){
//use Abraham\TwitterOAuth\TwitterOAuth;
//$twitteroauth = new TwitterOAuth(consumer_key, consumer_secret, oauth_access_token, oauth_access_token_secret);
$tweets = $twitteroauth->get($type . '/ids', array ( 'screen_name' => $term, 'cursor' => $next_cursor, 'count' => 50));
// Pause the loop for 16 min after every 15th request
if ($loop_num % 15 == 0 && $loop_num > 15) {
echo "sleep mode";
sleep(960);
echo "sleep mode done";
}
// set cursors
$previous_cursor = $next_cursor;
//echo 'Previous cursor is ' . $previous_cursor;
//echo '\n Next cursor is ' . $next_cursor;
foreach($tweets as $key => $val) {
if($key == "ids"){
//echo $val[0];
foreach($val as $value){
$value . "\n";
$content .= ",\n" . $value;
}
}
if($key == "next_cursor"){
//echo "\n \n";
$next_cursor = $val;
}
}
$loop_num ++;
echo "Type is now " . $type . "\n";
echo "Loop is " . $loop_num . " for " . $type . "\n";
file_put_contents($file, $content);
}
}
getFrindsFollowers($term, $type);
?>
Is most likely a easy fix but would appreciate any guidance on how to use a get request inside a function.
You are having trouble with scope (http://php.net/manual/en/language.variables.scope.php)
If you already have the twitteroauth variable defined outside the function, add this line at the start of it
global $twitteroauth;
This will give you access to the variable inside the function.

calling a function from another plugin wordpress

I am having problem with calling a function from another plugin it seems to return nothing tho this does work on other plugin
function caller_func()
{
if (!function_exists('form')) return;
return form($number = null);
}
function chrp1_get_popup(){
$chrp1_popup = '<div id="fullscre"></div>';
$chrp1__query= "post_type=popup-widget-details&showposts=1";
query_posts($chrp1__query);
if (have_posts()) : the_post();
$chrp1_mykey_values = get_post_custom_values('code');
$chrp1_descrip = get_the_content();
$chrp1_popup .= '<span onclick="chrp1_showall();">'.$chrp1_descrip.'</span>';
$chrp1_popup .= '<div id="newsox">';
$chrp1_popup .= '<img src="'.chrp1_PATH.'image/cross.png" class="ccross"
onclick="chrp1_getrid();" width="23"/>';
$getfunc = 'caller_func';
$chrp1_popup .= $getfunc();
$chrp1_popup .= '</div>';
endif; wp_reset_query();
return $chrp1_popup;
}
this code works on my other plugins I want to call but not this one below can anybody help
function form($number = null) {
if ($number == null)
return $this->subscription_form();
$options = get_option('newsletter_forms');
$form = $options['form_' . $number];
if (stripos($form, '<form') !== false) {
$form = str_replace('{newsletter_url}', plugins_url('newsletter/do/subscribe.php'), $form);
} else {
$form = '<form method="post" action="' . plugins_url('newsletter/do/subscribe.php') . '" onsubmit="return newsletter_check(this)">' .
$form . '</form>';
}
$form = $this->replace_lists($form);
return $form;
}
when I check the source code nothing from the form has loaded

How do i make this rss feed validate?

I was using this to generate RSS to post to my facebook wall... but in the last 24 hours it stopped working. I think that the feed pushing service i use became strict with the RSS validation. This doesnt validate... and i cant get it too. Can anyone suggest changes to make this work? I know this probably looks VERY messy! :os
Thanks in advance.
<?php do { ?>
<item>
<title><![CDATA[<?php echo htmlentities(strip_tags(addslashes($row_getDresses['listing_title']))); ?><?php if($_GET['type'] == "reduced-dresses"){?> (REDUCED BY <?php echo $row_getDresses['symbol'];?><?php echo $row_getDresses['reduced_price'];?> <?php echo $row_getDresses['dress_currency'];?>)<?php } else {?> (<?php echo $row_getDresses['symbol'];?><?php echo $row_getDresses['price'];?> <?php echo $row_getDresses['dress_currency'];?>)<?php }?>]]></title>
<link><![CDATA[http://www.asite.com/dress/<?php echo $row_getDresses['listing_tidy_url'];?>-<?php echo $row_getDresses['dress_id'];?>.html]]></link>
<description><![CDATA[<?php echo substr(strip_tags(addslashes(trim($row_getDresses['dress_desc'])),'ENT_QUOTES'),0,100);?>]]>...</description>
<?php if (isset($row_getDresses['main_image']) && file_exists("../listing-images/".$row_getDresses['main_image']."")) { ?>
<enclosure url="http://www.asite.com/listing-images/<?php echo $row_getDresses['main_image'];?>" length="<?php echo filesize("../listing-images/".$row_getDresses['main_image']."");?>" type="image/jpeg">
<?php }?>
<?php if ($_GET['type'] == "reduced-dresses"){?>
<pubDate><?php echo $row_getDresses['date_updated'];?> GMT</pubDate>
<?php } else { ?>
<pubDate><?php echo $row_getDresses['date_added'];?> GMT</pubDate>
<?php }?>
<category><?php echo htmlentities($pageTitle);?></category>
</item>
<?php } while ($row_getDresses = mysql_fetch_assoc($getDresses)); ?>
you dosn't close the enclosure-tag, add a </enclosure> or just add a / at the end of the tag like <enclosure ... />
Update
and readability was horible, here is an exemple at your code in my coding-style:
<?php
do
{
/* preper data */
$category = htmlentities($pageTitle);
$link = "http://www.asite.com/dress/{$row_getDresses['listing_tidy_url']}-{$row_getDresses['dress_id']}.html";
$description = substr(strip_tags(addslashes(trim($row_getDresses['dress_desc'])),'ENT_QUOTES'),0,100);
$title = htmlentities(strip_tags(addslashes($row_getDresses['listing_title'])));
/* Reduced price? */
if($_GET['type'] == "reduced-dresses")
{
$title .= " (REDUCED BY {$row_getDresses['symbol']}{$row_getDresses['reduced_price']} {$row_getDresses['dress_currency']})";
$date = $row_getDresses['date_updated'];
}
else
{
$titlt .= " ({$row_getDresses['symbol']}{$row_getDresses['price']} {$row_getDresses['dress_currency']})";
$date = $row_getDresses['date_added'];
}
/* image exists? */
if(isset($row_getDresses['main_image']) AND file_exists("../listing-images/".$row_getDresses['main_image'].""))
{
$image = "http://www.asite.com/listing-images/{$row_getDresses['main_image']}";
$image_size = filesize("../listing-images/".$row_getDresses['main_image']."");
}
else
{
$image = FALSE;
}
/* write RSS */
echo "<item>";
echo "<title><![CDATA[{$title}]]></title>";
echo "<link><![CDATA[{$link}]]></link>";
echo "<description><![CDATA[{$description}]]>...</description>";
if($image)
{
echo "<enclosure url='{$image}' length='{$image_size}' type='image/jpeg' />";
}
echo "<pubDate>{$date} GMT</pubDate>";
echo "<category>{$category}</category>";
echo "</item>";
} while ($row_getDresses = mysql_fetch_assoc($getDresses));
?>
I tried to make it a bit more readable and yes, enclosure was not closed:
<?php
$new_rss = '';
do {
$new_rss .= '<item>';
$new_rss .= '<title><![CDATA[' . htmlentities( strip_tags( addslashes( $row_getDresses[ 'listing_title' ] ) ) );
if( $_GET[ 'type' ] == 'reduced-dresses') {
$new_rss .= '(REDUCED BY ' . $row_getDresses[ 'symbol' ] . $row_getDresses[ 'reduced_price' ] . $row_getDresses[ 'dress_currency' ] . ')';
} else {
$new_rss .= '(' . $row_getDresses[ 'symbol' ] . $row_getDresses[ 'price' ] . $row_getDresses[ 'dress_currency' ] . ')';
}
$new_rss .= ']]></title>';
$new_rss .= '<link><![CDATA[http://www.asite.com/dress/' . $row_getDresses[ 'listing_tidy_url' ] . '-' . $row_getDresses[ 'dress_id' ] . '.html]]></link>';
$new_rss .= '<description><![CDATA[' . substr( strip_tags( addslashes( trim( $row_getDresses[ 'dress_desc' ] ) ), 'ENT_QUOTES' ), 0, 100 ) . ']]>...</description>';
if ( isset( $row_getDresses[ 'main_image' ] ) && file_exists( '../listing-images/' . $row_getDresses[ 'main_image' ] ) ) {
$new_rss .= '<enclosure url="http://www.asite.com/listing-images/' . $row_getDresses[ 'main_image' ] . '" length="' . filesize( '../listing-images/' . $row_getDresses[ 'main_image' ] ) . '" type="image/jpeg" />';
}
if ( $_GET[ 'type' ] == 'reduced-dresses' ) {
$new_rss .= '<pubDate>' . $row_getDresses[ 'date_updated' ] . ' GMT</pubDate>';
} else {
$new_rss .= '<pubDate>' . $row_getDresses[ 'date_added' ] . ' GMT</pubDate>';
}
$new_rss .= '<category>' . htmlentities($pageTitle) . '</category>';
$new_rss .= '</item>';
} while ( $row_getDresses = mysql_fetch_assoc( $getDresses ) );
echo $new_rss;
?>

Categories