Archive for the ‘Wordpress’ Category

WordPress Powerpress Youtube loop to show all posts with thumbnail

Tuesday, December 8th, 2015

Add a loop to index.php (Main Index Template) to show all the blog’s posts/youtube videos with thumbnails below the homepage most recent single post.

<?php
/* added loop to return all wordpress posts */
	$rPosts = new WP_Query();
    	$rPosts->query('showposts=-1');
    	while ($rPosts->have_posts()) : $rPosts->the_post();

/* retrieve custom 'enclosure' value, which contains the Youtube embed code, from each post */	
		$enclosure = get_post_custom_values('enclosure');

/* don't render it immediately so that we can see what we're getting back */
		$enclosure = str_replace("<iframe", "", $enclosure[0]);

/* turn html content into an array so that we can target the Youtube video id */
		$enclosure = explode("http://www.youtube.com/embed/",$enclosure);
		$enclosure = explode("?", $enclosure[1]);

/* append the video id onto the youtube thumbnail url */
		$final = "<img src='http://img.youtube.com/vi/$enclosure[0]/default.jpg' />";
		?>

/* display thumb wrapped in an anchor */
		<a href="<?php the_permalink(); ?>"><?php echo $final; ?></a>
<?php
	endwhile;
	wp_reset_query();
?>

WordPress Functions.php add_filter after comment redirect

Thursday, March 15th, 2012

add_filter(‘comment_post_redirect‘, ‘redirect_after_comment‘);
function redirect_after_comment()
{
wp_redirect($_SERVER[‘HTTP_REFERER‘]);
}

Create a php page with a form that searches (curls) two separate WordPress applications

Friday, July 29th, 2011

We have many installations where I work, some of them newer, some older, some severely whacked at by coders, some pretty much default installations.

Anyhow, now they want a page from which a visitor could enter a search term, click submit, and get results from all of the separate applications!

Here is my solution:

The new page has your basic self submitting form:

<form action=”” method=”post”>
<label for=”search”>Search:</label>
<input name=”s” type=”text” value=””  />
<input type=”submit” />
</form>

Then, of course, it grabs what has been submitted:

<?php

/**
* Get Search parameters
*/
$search = $_POST[‘s’];
$search = str_replace(” “,”%20”,$search);
echo $search;

?>

This checks to ensure that the user didn’t submit nothing (as WordPress would give us every post as currently coded…! ick).  This would also be a great place to guard against injection attacks (or in the last step of course), to filter what may be searched for, etc., but I’ll leave those concerns for another discussion:

<?php
/**
* If desired search is NOT empty, search, otherwise don’t
*/
if(($search != ”) && ($search != null) && (!empty($search)) )
{
?>

Now we curl in the results from each installation:

<?php
/**
* Get Search results from WP app 1
*/
$sub_req_url = “http://YOURAPP1URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

<?php
/**
* Get Search results from WP app 2
*/
$sub_req_url = “http://YOURAPP2URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

Now let’s close our IF block, and maybe provide ELSE if we want to…

<?php
/**
* close if empty block
*/
}
else
{
}
?>

Ok, that’s the end of our new page, again, I’ll leave formatting of the results and the rest of the page to another discussion.  Now let’s make the above mentioned search pages “searchpage.php” (make one for EACH APP, lives in the ROOT of EACH WP installation that we’re searching!):

<?php
/**
* WordPress App 1 Post Results Pull-In
*/
define(‘WP_USE_THEMES‘, true);
include(‘wp-load.php’ );
$query = new WP_Query(‘s=’ . $_GET[‘s’]);
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>

/* Again, how you choose to skin the results could be implemented here, but I’ll leave that up to you… */

<div id=”post-<?php the_ID(); ?>“>
<h2><?php the_title(); ?></h2>
<div>
<?php the_content(‘<p>Read the rest of this page &raquo;</p>‘); ?>
<?php wp_link_pages(array(‘before’ => ‘<p><strong>Pages:</strong> ‘, ‘after’ => ‘</p>‘, ‘next_or_number’ => ‘number’)); ?>
</div>
</div>
<?php endwhile; endif; ?>

Whoohoo! Great Work!

WordPress base url path for multiple platform development links

Thursday, June 30th, 2011

so that anchor tags always nicely point to your application root use:

get_bloginfo('url')

http://codex.wordpress.org/Template_Tags/get_bloginfo

WordPress the_excerpt() strips html tags, create a custom function to leave them in

Friday, May 27th, 2011

go to your theme’s function script:

wp-content/themes/yourthemename/function.php

at the top insert the following (add to ‘<img>’ below to NOT strip out other specific tags, or simply comment the line out…):

function improved_trim_excerpt($text) {
global $post;
if ( ” == $text ) {
$text = get_the_content(”);
$text = apply_filters(‘the_content’, $text);
$text = str_replace(‘]]>’, ‘]]&gt;’, $text);
$text = strip_tags($text, ‘<img>’);
$excerpt_length = 55;
$words = explode(‘ ‘, $text, $excerpt_length + 1);
if (count($words)> $excerpt_length) {
array_pop($words);
array_push($words, ‘[…]’);
$text = implode(‘ ‘, $words);
}
}
return $text;
}
remove_filter(‘get_the_excerpt’,’wp_trim_excerpt’);
add_filter(‘get_the_excerpt’,’improved_trim_excerpt’);

some references: http://codex.wordpress.org/Function_Reference/the_excerpt, http://www.aaronrussell.co.uk/blog/improving-wordpress-the_excerpt/

WordPress convert podcast from Podpress to Powerpress support HTML5 mobile devices

Thursday, May 12th, 2011

If you found this post, you think you’re stuck with Podpress, and/or you’re wanting to make your podcast viewable on mobile devices.  I was in the same boat until just recently, stuck with a podcast I’d initially setup with Podpress years ago, support for which has been worryingly spotty and dwindling, wishing I could now ditch Podpress, but I had over 160 posts I didn’t want to convert….

What I didn’t realize is that the creators of Powerpress had exactly that in mind when they developed Powerpress!  All I had to do was install Powerpress, activate it, ensure that it’s settings were correct, and then deactivate Podpress, and bam, it worked. SO AWESOME, highly recommended.

So I can successfully declare today, that I’ve migrated now 3 podcasts from Podpress to Powerpress, one with 84 posts, one with 164, another with 11.

  • The feeds are unaffected, Feedburner is completely unaware of the change
  • views/layouts unaltered
  • I didn’t even need to go back into the posts and alter the data, Powerpress simply interprets it
  • iTunes unaffected
  • Powerpress serves up the flashplayer if the requesting browser support flash, and theL HTML5 audio or video player if it doesn’t, enabling by many versions of the iPod, iPad, Android, and so on, handled, done!
  • HUGE win.

Persistence of GET URL parameters passed to WordPress site with Permalink clean pretty URLs turned on

Friday, April 15th, 2011

Here’s the scenario:
We have a store site.
The store site has a link on its homepage that leads to a wordpress site.
When a visitor clicks the link,
we want a url parameter that is passed with the visitor to the wordpress site
to remain in the url
so that when/if they click a link in the wordpress site that leads back to the store,
the parameter comes back with them.

Normally, you’d simply add a $_GET in your theme somewhere,
assign it to a variable,
and then append that onto any links that are headed back to the store site.

The trouble, though, is that when WordPress’
clean and pretty Permalinks URL function is active,
it takes over, and forwards (via htaccess, wordpress base code functions, or otherwise),
at which point in time data passed over is lost.

Solution:
In WordPress’ index.php (the very first root directory index),
include another file.

include(‘passback.php’);

In that file, instantiate SERVER SESSIONS, and save received parameters.
Something like this (of course looping through the REQUEST parameters dynamically would be smarter, but for simplicities sake, let’s just target a particular parameter):

session_start();
if($_GET[‘persistme’] != ”){ $passit = $_GET[‘persistme’]; }
if(!isset($_SESSION[‘passback’])){ $_SESSION[‘passback’] = $passit; }

Now you can include your passback retrieval class in your theme, grab the parameter, and use your JavaScript library of choice to loop through all the links in the page and append it onto them.
Something like this (Prototype, and only appending links that already have a ? and thus other parameters they’re sending back…):

document.observe(‘dom:loaded’, function() {
$$(“a”).each(function(a) {
newhref = a.href;
if(newhref.include(‘?’){
newhref = a.href + “?rememberme=<?php echo $passit; ?>”;
a.writeAttribute(‘href’, newhref);
}
});
});

iTunes remove podcast example rss xml feed itunes:block

Thursday, March 3rd, 2011

So you submitted your podcast, with a post containing placeholder content because you had to have it approved and live by some deadline, but now it’s deemed not presentable, because marketing has changed the title last minute, and as you change this first post’s content via its RSS feed, some of it changes, the dynamic parts most likely, the media, and so on, but the title isn’t changing in the iTunes store…

In my example, I used a feedburner feed (iTunes is using that), so I can simply change the feed source in feedburner, to something like the example xml feed in this post, and we can at least get the eyesore out of iTunes, freeing us up to make a new feedburner feed, and re-submit THAT anew to iTunes for a fresh clean go of things…

Host something like this somewhere, and point the old feedburner feed to it, done.

<?xml version=”1.0″ encoding=”UTF-8″?>
<rss xmlns:itunes=”http://www.itunes.com/dtds/podcast-1.0.dtd” version=”2.0″>
<channel>
<itunes:block>yes</itunes:block>
<title>A Title Is Required For The Feed To Validate</title>
</channel>
</rss>

WordPress determine version number

Wednesday, February 23rd, 2011

wp-includes/version.php

WordPress custom sidebar category filtered archive code

Wednesday, February 23rd, 2011

<div id=”sidebar”>
<ul>
<?php
$myposts = get_posts(“category=1”);
foreach($myposts as $post) : ?>
<li><a href=”<?php the_permalink(); ?>“><?php the_time(‘M’) ?>. – <?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
</div>

mostly in thanks to:

http://www.z-oc.com/blog/2008/03/category-based-archive/

http://www.themightymo.com/2009/07/22/includeexclude-category-from-wordpress-wp_get_archives/

http://kwebble.com/blog/2007_08_15/archives_for_a_category

WordPress Post to Category ID association in the Database

Wednesday, February 23rd, 2011

WordPress 3

Start with a Post and get Category ID:

Get the id number(A) for the post you’re interested in in wp_posts table,  id column

Go to wp_term_relationships table, and find that same id number(A) in the object_id column, read over to the term_taxonomy_id column and get that number, that’s the category id

Start with a Category ID and get Category Name:

Go to the wp_terms table, and find the category you’d like in the name column, read over to the term_id and note the number

Find all Cateogry IDs:

Go to the wp_term_taxonomy table and sort by taxonomy value ‘category category number is in term_taxonomy_id column

WordPress control number of posts per archive page

Wednesday, February 16th, 2011

edit archive.php

replace this:

< ?php get_header(); ? >

with something along these lines:

< ?php get_header(); ? >
< ?php
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$args=array(
‘showposts’ => 10,
‘paged’=>$paged,
‘caller_get_posts’=> 1
);
query_posts($args);
? >

WordPress affect categories search form searches – solution 2

Tuesday, January 18th, 2011

Please see this post if you’re only wanting to limit the form to a single category, as it’s as simple as adding a hidden form field.

This solution uses functions.php, adding something like the following:

function SearchFilter($query)
{
if($query->is_search){
$query->set(‘cat’,’0′);
}
}
add_filter(‘pre_get_posts’,’SearchFilter’);

similar post:
http://alexyz.com/wordpress-rss-feed-exclude-categories-or-only-serve-one-particular-category/

http://alexyz.com/wordpress-limit-search-form-to-a-category-2/

similar reference:

http://speckyboy.com/2010/09/19/10-useful-wordpress-search-code-snippets/

WordPress creating users in MySQL via script wp_user_level wp_capabilities wp_users

Monday, January 3rd, 2011

Scenario:
Creating a WordPress blog with an entire company of users.
We want employees to already have an account, so that registration may be turned OFF otherwise.
From an excel list of employees, we’ll extract their email, make an account for each email in the WordPress database, and then they may change their passwords themselves. You can imagine what the php script will look like, to extract the email, and foreach insert the following (uniqueusername and 5 replaced of course with incrementing id numbers and changing emailnames@ourcompany.com):

 

INSERT INTO wp_users
(id,user_login,user_pass,user_email,display_name)
VALUES
(‘5′,’uniqueusername’,md5(‘pass’),’uniqueusername@ourcompany.com’,’uniqueusername’);

 

// to note, this below is simultaneously a nice example of how to insert multiple rows with one MySQL INSERT statement

 

INSERT INTO wp_usermeta
(user_id,meta_key,meta_value)
VALUES
(‘5′,’wp_capabilities’,’a:1:{s:6:”author”;s:1:”1″;}’),
(‘5′,’wp_user_level’,’10’);

 

Thus, the full script looks something like this:

 

$employees = array(’employee1@somesite.com’,’employee2@somesite.com’,’employee3@somesite.com’,’andsoon…’);

 

$startNumber = 10; // if you already have users, pick the next highest number, as it uses this for several tables below, we need them to happen at the same time so that attributes belong to specific users…

 

$db_name = “databasename”;
$db_host = “localhost”;
$db_username = “username”;
$db_password = “password”;

 

// note the nice error reporting so that we can troubleshoot connections, users, table selections, and so forth…
$link = mysql_connect($db_host, $db_username, $db_password);
if (!$link) {
die(‘Could not connect: ‘ . mysql_error());
}
else
{
echo ‘Connected successfully<br />’;
}

 

$db_selected = mysql_select_db($db_name, $link);
if (!$db_selected) {
die (‘Can\’t use foo : ‘ . mysql_error());
}
else
{
echo ‘Selected manyvoices database successfully<br />’;
}

 

foreach($employees as $employee)
{
list($user_name, $therest) = explode(‘@’,$employee);

 

$query1 = “INSERT INTO wp_users
(id,user_login,user_pass,user_email,display_name)
VALUES
(‘” . $startNumber . “‘,'” . $user_name . “‘,md5(‘pass’),'” . $employee . “‘,'” . $user_name . “‘)
“;
//echo $query1 . “<br />”;

 

$result1 = mysql_query($query1);
if(!result1){
die(‘Error: ‘ . mysql_error());
}
else{
echo “User: ” . $user_name . ” : Added<br />”;
}

 

$query2 = “INSERT INTO wp_usermeta
(user_id,meta_key,meta_value)
VALUES
(‘” . $startNumber . “‘,’wp_capabilities’,’a:1:{s:6:\”author\”;s:1:\”1\”;}’),
(‘” . $startNumber . “‘,’wp_user_level’,’10’)
“;
//echo $query2 . “<br />”;

 

$result2 = mysql_query($query2);
if(!result2){
die(‘Error: ‘ . mysql_error());
}
else
{
echo “User Credentials: ” . $user_name . ” : Updated<br />”;
}

 

$startNumber++;
}

 

mysql_close($link);

 

 

Snippets: HTML object swf embed within a WordPress post snag it n’ publish it code excerpt

Wednesday, December 29th, 2010

<object height=”24″ width=”500″ codebase=”http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0″ classid=”clsid:D27CDB6E-AE6D-11cf-96B8-444553540000″><param value=”file=http://www.site.net/track.mp3&amp;image=http://www.site.net/trackImage.jpg” name=”flashvars”><param value=”http://www.site.com/swf/player.swf” name=”movie”><embed height=”24″ width=”500″ flashvars=”file=http://www.site.net/track.mp3″ pluginspage=”http://www.macromedia.com/go/getflashplayer” type=”application/x-shockwave-flash” src=”http://www.site.com/swf/player.swf”></object>

WordPress RSS feed exclude categories or only serve one particular category

Monday, December 27th, 2010

// This will make the site feed ONLY contain category id 9.

add to wp-content/themes/your-active-theme/function.php

function myFilter($query) {
if ($query->is_feed) {
$query->set(‘cat’,’9′);
}
return $query;
}

add_filter(‘pre_get_posts’,’myFilter‘);

// To EXCLUDE categories 9 and 11:

function myFilter($query) {
if ($query->is_feed) {
$query->set(‘cat’,’-9, -11‘);
}
return $query;
}

add_filter(‘pre_get_posts’,’myFilter‘);

WordPress Custom Structure URL Permalinks

Monday, December 13th, 2010

Admin

Settings

Permalinks

Custom Structure radio text entry field

use this:

/%postname%/

so that your posts appear as they do in this blog, here:

http://www.sitename.com/post-name

httpd.conf or .htaccess for apache WordPress redirect

Monday, December 13th, 2010

This is simply a note to save this block of code should I need it again.

The server in question is one of many cloud instances, and local development machines, in an environment using PHP, JAVA, Surf, among other technologies.

In short, it’s a pretty complex implementation/configuration…

Some URLs are being rewritten, others forwarded, directory crawling is off, but…

a legacy WordPress blog is being converted to clean/pretty URLs for SEO purposes

(which “look” like directory folder URLs)

(rather than WordPress relying on URL parameters by default)

so, along with editing the WordPress Setting for this,

the following was added to the httpd.conf file:

<IfModule modrewrite.c>

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /podcastInQuestionFolder/index.php [L]

</IfModule>

Of course, quite similar code in the .htaccess within that folder would accomplish a similar aim.

WordPress limit search form to a category

Thursday, December 9th, 2010

example:

 

<script>
function submitter()
{
track_it(‘/podcast/searchFormSubmit/’);
document.searchform.submit();
}

</script>

 

<form method=”get” name=”searchform” id=”searchform” action=”<?php bloginfo(‘url’); ?>/”>

 

<input type=”text” value=”<?php the_search_query(); ?>” name=”s” id=”s” onclick=”this.value=””/>

 

This is the important new line, 5 is an example category id

 

<input type=”hidden” name=”cat” value=”5″ />

 

<a href=”javascript:submitter()” style=”text-decoration:none;font-size:11px;margin:0 0 0 5px;position:absolute;top:0px;”><img src=”wp-content/themes/New/images/go.png” onmouseover=”this.src=’wp-content/themes/New/images/go-over.png'” onmouseout=”this.src=’wp-content/themes/New/images/go.png'” border=”0″ />

 

</a>
</form>

 

source: http://wpgarage.com/code-snippets/how-to-hack-the-wordpress-search-function-search-categories-and-child-categories/

 

WordPress Visual editor inactive

Thursday, December 9th, 2010

All of a sudden you can’t click on your visual editor tab when adding a post?
Did you recently install a new plug-in?
Disable it and try again.
It isn’t compatible with your current version…
Just a short note.

Podpress Plugin WordPress Outside the Loop Single page

Thursday, October 21st, 2010

Am building a page that pulls in a single post from a WordPress podcast site that I built that uses Podpress. The long and short of it is that it requires instantiating the WordPress app externally, and using a mini-loop, pretty straight forward, but for the longest time I couldn’t figure out for the life of me why the Podpress player wasn’t showing up…

Instead, I was only getting the [display_podcast] token that one places in a post for Podpress and WordPress to then replace upon rendering the post…

I knew there had to be a simple solution.  My final code is below.  The key: wp_head();

< ? php

require_once(‘../podcast/wp-load.php’ ); // load the app
wp_head(); // this gets all the plugins and dependencies!!!!
query_posts(‘p=1807’); // documentation on using query_posts is nice and simple and clear
while (have_posts()) : the_post(); // iterate over the return

// use various things to output the data

the_ID(); the_time(‘l, F j, Y’); the_title(); the_content(); // and so on

endwhile;

? >

WordPress PHP custom theme functions.php hook

Wednesday, July 28th, 2010

In your theme (wp-content/themes/YourNewTheme) create or find functions.php

and start making whatever you need.  It’s a nice clean place to put things without hacking away at your code,

dynamically inserting with JS, or whatever other measure you’ve either employed in the past, or are considering now…

for example,

<?php
//My own footer hook
function my_footer() {

//code to execute

?><div class=”bigText”>blah blah blah</div><?

}

?>

then, wherever you like, call your new function, example, replace all <? wp_footer(); ?> calls with, you guested it, <? my_footer(); ?>

thanks to: http://www.raymondselda.com/understanding-action-hooks-in-wordpress/

Don’t forget to include the following in your new custom theme functions.php file if you want the dynamic custom drag widget sidebar!:

if ( function_exists(‘register_sidebar’) )
register_sidebar();

reference: http://codex.wordpress.org/Widgetizing_Themes

Moving WordPress DB changes and/or functions.php

Thursday, March 25th, 2010

change DB values

table:
wp-options

column:
option_name

fields:
siteurl
home

also to note in here:
blogname
upload_url_path
comment_moderation
rss_language
admin_email

ALTERNATE OPTION, (db inaccessible)
add a few lines to:
wp-content/themes/default/functions.php

lines:
update_option(‘siteurl’,’http://yourUrl‘);
update_option(‘home’,’http://yourUrl/soundstrue.com/podcast‘);

If the second option used not to be forgotten, as it will overwrite DB every time App loads…

WordPress Akismet (spam)

Monday, March 22nd, 2010

WordPress comes with the Akismet plugin.

Use it.

Reference: http://akismet.com/

How:

Create a dashboard.wordpress.com account  if you don’t already have one, & find your API key

then in your blog, activate the Akismet plugin, enter your key, reap the rewards.

This Blog proudly uses the following Widget Plugins

Thursday, March 18th, 2010

Google AdSense Widget

http://wordpress.smullindesign.com/plugins/google-adsense-widget

Google XML Sitemaps

http://www.arnebrachhold.de/redir/sitemap-home/

Simple Hit Counter

http://jungwirths.com/2009/03/simple-wordpress-hit-counter-plugin/

WP Simple Paypal Donation

http://www.tipsandtricks-hq.com/?page_id=942

Exec PHP

http://bluesome.net/post/2005/08/18/50/

Deactivate Visual Editor

http://plugindve.wordpress.com/

Google Analytics for WordPress

http://yoast.com/wordpress/analytics/#utm_source=wordpress&utm_medium=plugin&utm_campaign=google-analytics-for-wordpress

WordPress SESSIONS

Thursday, March 4th, 2010

simply add:

session_start();

to the start of:

wp-config.php

right at the top, after <?

If homepage : do a second “Loop” to show current article “post” WordPress

Thursday, March 4th, 2010

<? if(is_front_page()) : ?>
<? query_posts(‘showposts=1’); ?>
<?php while (have_posts()): the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<p><a href=”<?php the_permalink(); ?>“>Read more…</a></p>
<?php endwhile; ?>
<? endif; ?>