Snippets

•October 31, 2009 • Leave a Comment

1.

Popular Posts

2.

    3. get_results(“SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5″);
    4. foreach ($result as $post) {
    5. setup_postdata($post);
    6. $postid = $post->ID;
    7. $title = $post->post_title;
    8. $commentcount = $post->comment_count;
    9. if ($commentcount != 0) { ?>
    10.
  • <a href="%3C?php%20echo%20get_permalink%28$postid%29;%20?%3E" title="”>
    11. {}
  • 12.
    13.
    14.

——————————————–
1. ID);
4. if ($tags) {
5. echo ‘Related Posts’;
6. $first_tag = $tags[0]->term_id;
7. $args=array(
8. ‘tag__in’ => array($first_tag),
9. ‘post__not_in’ => array($post->ID),
10. ’showposts’=>5,
11. ‘caller_get_posts’=>1
12. );
13. $my_query = new WP_Query($args);
14. if( $my_query->have_posts() ) {
15. while ($my_query->have_posts()) : $my_query->the_post(); ?>
16.
17. <a href="%3C?php%20the_permalink%28%29%20?%3E" rel="bookmark" title="Permanent Link to “>
18.
19.

——————————

1. function catch_that_image() {
2. global $post, $posts;
3. $first_img = ”;
4. ob_start();
5. ob_end_clean();
6. $output = preg_match_all(‘//i’, $post->post_content, $matches);
7. $first_img = $matches [1] [0];
8.
9. if(empty($first_img)){ //Defines a default image
10. $first_img = “/images/default.jpg”;
11. }
12. return $first_img;
13. }
—————————

1. function catch_that_image() {
2. global $post, $posts;
3. $first_img = ”;
4. ob_start();
5. ob_end_clean();
6. $output = preg_match_all(‘//i’, $post->post_content, $matches);
7. $first_img = $matches [1] [0];
8.
9. if(empty($first_img)){ //Defines a default image
10. $first_img = “/images/default.jpg”;
11. }
12. return $first_img;
13. }

———————–

returns all images from a post

1.
2.
3.
4. post_content;
6. $szSearchPattern = ‘~]*\ />~’;
7.
8. // Run preg_match_all to grab all the images and save the results in $aPics
9. preg_match_all( $szSearchPattern, $szPostContent, $aPics );
10.
11. // Check to see if we have at least 1 image
12. $iNumberOfPics = count($aPics[0]);
13.
14. if ( $iNumberOfPics > 0 ) {
15. // Now here you would do whatever you need to do with the images
16. // For this example the images are just displayed
17. for ( $i=0; $i
———————————

First open the “single.php” in your theme folder and save it as “image.php” in same folder. Now open “image.php” and search the line which displays the post content. It should be somewhat in the following form. It can differ a bit but the function is called by the_content like this
view plaincopy to clipboardprint?

1.

Now insert the following code above the aforementioned code (the_content).

1.

2. ID, ‘medium’ ); ?>
3.
4.

5. post_excerpt) ) the_excerpt(); // this is the “caption” ?>
6.

Also insert the following code below the aforementioned code (the_content).

1.

2.

3.

4.

5.
6.

Now, add this CSS to your theme’s style.css file
view plaincopy to clipboardprint?

1. /****************Image Gallery *********************/
2. .gallery {text-align:center;}
3. .gallery img {padding:2px; height:100px; width:100px;}
4. .gallery a:hover {background-color:#ffffff;}
5. .attachment {text-align:center;}
6. .attachment img { padding:2px; border:1px solid #999999;}
7. .attachment a:hover {background-color:#FFFFFF;}
8. .imgnav {text-align:center;}
9. .imgleft {float:left;}
10. .imgleft a:hover {background-color:#FFFFFF;}
11. .imgleft img{ padding:2px; border:1px solid #999999; height:100px; width:100px;}
12. .imgright {float:right;}
13. .imgright a:hover {background-color:#FFFFFF;}
14. .imgright img{ padding:2px; border:1px solid #999999; height:100px; width:100px;}

Now to use this gallery, just upload your images in a post or a page, go to the gallery option (after you have finished uploading all your images) and insert gallery into your post/page

TWITTER

1. Share on Twitter
————————-

1. //get cool feedburner count
2. $whaturl=”http://api.feedburner.com/awareness/1.0/GetFeedData?uri=feedburner-id”;
3.
4. //Initialize the Curl session
5. $ch = curl_init();
6.
7. //Set curl to return the data instead of printing it to the browser.
8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
9.
10. //Set the URL
11. curl_setopt($ch, CURLOPT_URL, $whaturl);
12.
13. //Execute the fetch
14. $data = curl_exec($ch);
15.
16. //Close the connection
17. curl_close($ch);
18. $xml = new SimpleXMLElement($data);
19. $fb = $xml->feed->entry['circulation'];
20. //end get cool feedburner count

Now paste this anywhere you want and it’ll display a Feedburner subscriber count in text.

————————-
1. function publish_later_on_feed($where) {
2. global $wpdb;
3.
4. if ( is_feed() ) {
5. // timestamp in WP-format
6. $now = gmdate(‘Y-m-d H:i:s’);
7.
8. // value for wait; + device
9. $wait = ‘5′; // integer
10.
11. // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
12. $device = ‘MINUTE’; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
13.
14. // add SQL-sytax to default $where
15. $where .= ” AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, ‘$now’) > $wait “;
16. }
17. return $where;
18. }
19.
20. add_filter(‘posts_where’, ‘publish_later_on_feed’);

———————
How to Exclude Categories from Your RSS Feed

1. function myFilter($query) {
2. if ($query->is_feed) {
3. $query->set(‘cat’,'-5′); //Don’t forget to change the category ID =^o^=
4. }
5. return $query;
6. }
7.
8. add_filter(‘pre_get_posts’,'myFilter’);
————————-

TWITTER HACKS

1. <a href="http://twitter.com/home?status=Currently reading ” title=”Send this page to Twitter!” target=”_blank”>Spread on Twitter

1. function getTinyUrl($url) {
2. $tinyurl = file_get_contents(“http://tinyurl.com/api-create.php?url=”.$url);
3. return $tinyurl;
4. }

1. ID));
3. echo ‘Tiny Url for this post: ‘.$turl.’
4. ?>

——————-

1. function string_getInsertedString($long_string,$short_string,$is_html=false){
2. if($short_string>=strlen($long_string))return false;
3. $insertion_length=strlen($long_string)-strlen($short_string);
4. for($i=0;$i<strlen ($short_string);++$i){
5. if($long_string[$i]!=$short_string[$i])break;
6. }
7. $inserted_string=substr($long_string,$i,$insertion_length);
8. if($is_html && $inserted_string[$insertion_length-1]=='<'){
9. $inserted_string='saveHTML();
16. $element->parentNode->removeChild($element);
17. $html2=$document->saveHTML();
18. return string_getInsertedString($html,$html2,true);
19. }
20.
21. function getFollowers($username){
22. $x = file_get_contents(“http://twitter.com/”.$username);
23. $doc = new DomDocument;
24. @$doc->loadHTML($x);
25. $ele = $doc->getElementById(‘follower_count’);
26. $innerHTML=preg_replace(‘/^]*>(.*)]*>$/’,”\\1″,DOMElement_getOuterHTML($doc,$ele));
27. return $innerHTML;
28. }

1.
——————————–

allows us to pull the latest tweet from a Twitter user via the RSS feed that is produced by Twitter.

1. Twitter
————————–
1. <?php
2. $username = "TwitterUsername"; // Your twitter username.
3. $prefix = ""; // Prefix – some text you want displayed before your latest tweet.
4. $suffix = ""; // Suffix – some text you want display after your latest tweet.
5. $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";
6.
7. function parse_feed($feed) {
8. $stepOne = explode("”, $feed);
9. $stepTwo = explode(“”, $stepOne[1]);
10. $tweet = $stepTwo[0];
11. $tweet = str_replace(“<", "”, “>”, $tweet);
13. return $tweet;
14. }
15.
16. $twitterFeed = file_get_contents($feed);
17. echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);
18. ?>

——————-

pull multiple tweets from multiple user accounts and display them

1. <?php
2. $usernames = "Username Username Username"; // Pull from accounts, separated by a space
3. $limit = "5"; // Number of tweets to pull in, total.
4. $show = 1; // Show username? 0 = No, 1 = Yes.
5.
6. $prefix = ""; // This comes before the entire block of tweets.
7. $prefix_sub = ""; // This comes before each tweet on the feed.
8. $wedge = ""; // This comes after the username but before the tweet content.
9. $suffix_sub = "
"; // This comes after each tweet on the feed.
10. $suffix = ""; // This comes after the entire block of tweets.
11.
12. function parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub) {
13.
14. $usernames = str_replace(" ", "+OR+from%3A", $usernames);
15. $feed = "http://search.twitter.com/search.atom?q=from%3A" . $usernames . "&rpp=" . $limit;
16. $feed = file_get_contents($feed);
17. $feed = str_replace("&", "&", $feed);
18. $feed = str_replace("<", "”, “>”, $feed);
20. $clean = explode(“”, $feed);
21. $amount = count($clean) – 1;
22.
23. for ($i = 1; $i <= $amount; $i++) {
24.
25. $entry_close = explode("”, $clean[$i]);
26. $clean_content_1 = explode(“”, $entry_close[0]);
27. $clean_content = explode(“”, $clean_content_1[1]);
28. $clean_name_2 = explode(“”, $entry_close[0]);
29. $clean_name_1 = explode(“(“, $clean_name_2[1]);
30. $clean_name = explode(“)”, $clean_name_1[1]);
31. $clean_uri_1 = explode(“”, $entry_close[0]);
32. $clean_uri = explode(“”, $clean_uri_1[1]);
33.
34. echo $prefix_sub;
35. if ($show == 1) { echo “” . $clean_name[0] . “” . $wedge; }
36. echo $clean_content[0];
37. echo $suffix_sub;
38.
39. }
40. }
41. echo $prefix;
42. parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub);
43. echo $suffix;
44. ?>

———————–
1.

———————–
1.

———————

1.

———————–

Show recent post by category

•October 8, 2009 • Leave a Comment
- Show recent Posts

    <h2>Recent Posts</h2>

    <ul>
    <?php get_archives(‘postbypost’, 6); ?>
    </ul>

- Show recent posts from specific category ?

    <ul>
    <?php $recent = new WP_Query(“cat=1&showposts=5″);
    while($recent->have_posts()) : $recent->the_post();?>
    <li><a href=”<?php the_permalink() ?>” rel=”bookmark”>
    <?php the_title(); ?>
    </a></li>
    <?php endwhile; ?>
    </ul>

Posted via email from Netlex’s codebox

WP : loop full article + excerpt

•October 8, 2009 • Leave a Comment

<?php if (have_posts()) : ?>
    <?php $count = 0; ?>

   

    <?php while (have_posts()) : the_post(); ?>
        <?php $count++; ?>

       
        <h3>Title: </h3>
        <h4>Date: <?php echo date(“l, F d, Y”); ?> | <?php comments_number(); ?></h4>

        <?php if ($count == 1) : ?>

            <?php the_content(); ?> // display the full content of the first post only

            <h4>Please subscribe to my feed!</h4>

        <?php else : ?>

           
            <?php the_excerpt(); ?> // display only the excerpt for all other posts

            // for all posts except the first, process this code below each post

        <?php endif; ?>

        // for each post, including the first, process any code included here
        // any code output will be displayed below the content of every post

                        <h4>This is post #<?php the_ID(); ?> | Author: <?php the_author(); ?></h4>
        <p>Filed under: <?php the_category(‘,’); ?> | <?php edit_post_link(); ?></p>

    <?php endwhile; ?>

    // stop the post loop and process any code included here only once
    // any code output will be displayed below the entire set of posts

                <h4><?php posts_nav_link() ?><?php previous_post_link(); ?> •
        <?php posts_nav_link() ?><?php next_post_link(); ?></h4>

    <?php else : ?>

    // if there are no posts to display, process any code that is included here
    // the output of any code included here will be displayed instead of posts

              <p>Sorry, no posts matched your criteria.</p>

<?php endif; ?>

// any code included here occurs after the wordpress loop and is always displayed
<h6>Copyright &copy; <?php echo get_settings(‘home’); ?>/”><?php bloginfo(‘name’); ?></a> <?php echo date(‘Y’); ?></h6>

Posted via email from Netlex’s codebox

Hacks 4 WordPress

•June 15, 2009 • Leave a Comment

1.

Popular Posts

2.

    3. get_results(“SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5″);
    4. foreach ($result as $post) {
    5. setup_postdata($post);
    6. $postid = $post->ID;
    7. $title = $post->post_title;
    8. $commentcount = $post->comment_count;
    9. if ($commentcount != 0) { ?>
    10.
  • <a href="%3C?php%20echo%20get_permalink%28$postid%29;%20?%3E" title="”>
    11. {}
  • 12.
    13.
    14.

——————————————–
1. ID);
4. if ($tags) {
5. echo ‘Related Posts’;
6. $first_tag = $tags[0]->term_id;
7. $args=array(
8. ‘tag__in’ => array($first_tag),
9. ‘post__not_in’ => array($post->ID),
10. ’showposts’=>5,
11. ‘caller_get_posts’=>1
12. );
13. $my_query = new WP_Query($args);
14. if( $my_query->have_posts() ) {
15. while ($my_query->have_posts()) : $my_query->the_post(); ?>
16.
17. <a href="%3C?php%20the_permalink%28%29%20?%3E" rel="bookmark" title="Permanent Link to “>
18.
19.

——————————

1. function catch_that_image() {
2. global $post, $posts;
3. $first_img = ”;
4. ob_start();
5. ob_end_clean();
6. $output = preg_match_all(‘/<img .+src="['"]([

Post thumbnails with WordPress 2.5

•April 13, 2008 • Leave a Comment

Mysql + tableaux

•October 18, 2006 • Leave a Comment

Compteur

if (count($TABLEAU)>0):
ksort($TABLEAU);
While (List($KEY,$VALUE)=each($TABLEAU)):
echo (“$KEY -> $VALUE”);
EndWhile;
Endif;

Les tableaux php
_______________________

# connection SQL et ouverture de la base

mysql_connect(“localhost”,”root”,”");

mysql_select_db(“test”);
$res = mysql_query(“select distinct anneR from bfone order by anneR “) ;
$nbans = 0 ;
while ($ligr=mysql_fetch_array($res)) {
$nbans++ ; $ans[$nbans] = $ligr["anneR"] ;
} ; # fin de tant que

A Problèmes et erreurs communes MySQL 5.0.0 alpha

Bash script and cron (Cgi + Perl + Cron)

•October 18, 2006 • Leave a Comment

“TUTORIAL / www.cgi-interactive-uk.com

Bash Shell Script (mysqlbackup)

#!/bin/sh
mysqldump -uroot -ppwd –opt db1 > /sqldata/db1.sql
mysqldump -uroot -ppwd –opt db2 > /sqldata/db2.sql

cd /sqldata/
tar -zcvf sqldata.tgz *.sql
cd /scripts/
perl emailsql.cgi

The first mysqldump statement has 4 parameters passed to it :-

* -u = your MySQL username. (substitute root with your username)
* -p = your MySQL password. (substitute pwd with your password)
* –opt adds the most common and useful command line options, resulting in the quickest possible export. This option automatically includes –add-drop-table, –add-locks, –extended-insert, –quick and –use-locks.
* the database name to extract. (substitute db1 with your database name)
* the > /sqldata/db1.sql redirects all the output to a file called db1.sql in a directory /sqldata/.

Perl script (emailsql.cgi)

After creating the script, you need to make it executable by CHMODing the file permissions to 700.

#!/usr/bin/perl -w

use MIME::Lite;

$msg = MIME::Lite->new(

From => mysqlbackup@yoursite.co.uk,
To => you@yoursite.co.uk,
Subject => sqldata.tgz MySQL backup!,
Type => text/plain,
Data => “Hi You,\n MySQL database backups.”);

$msg->attach(Type=>application/x-tar,
Path =>”/sqldata/sqldata.tgz”,
Filename =>”sqldata.tgz”);

$msg->send;

Adding the Script to Cron

0 2 * * * /myscripts/mysqlbackup
0 5 * * 0 /myscripts/reindex

There are five fields for setting the date and time separated by a space, followed by the name of the script you wish to run. The five time settings are in the following order.

* Minutes – in the range of 0 – 59
* Hour – in the range of 0 – 23
* Day of month – in the range 1 – 31
* Month – in the range 1 -12
* Day of week – in the range 0 – 6 (0 = Sunday)

Any field with a * means run every possible match, so for example a * in the day of month field will run the script every single day of the month at the specified time. (…)

The above example shows my current crontab. The file has two entries, one for each script I wish to run. The first entry tells cron to run the mysqlbackup script every morning at 2am. The second entry runs my search engine indexer every Sunday morning at 5am.”

How to backup your MySQL tables and data every night using a bash script and cron CGI interactive

Cron tab + mod perl

# every monday rebuild all, including pdf
30 03 * * 1 /usr/local/modperl-docs/bin/site_build_force_pdf_index
# update all (only changes/no pdf) every 6 hours
15 6,12,18 * * * /usr/local/modperl-docs/bin/site_build_index
# update all (only changes and pdfs) once a day
15 0 * * * /usr/local/modperl-docs/bin/site_build_pdf_index

The mod_perl documentation

_____________________

Tutorial sur l’utilisation de Mysql avec Perl

CRON

[UNIX] Crontab mkaz.com

Pycron

Internals: Replacing Task Scheduler with Cron

Client-side and Server-side encoding

•October 15, 2006 • Leave a Comment

Récupérer les accents français quand MySql parle latin… au lieu de UTF-8

Apache Server 2.0.54
PHP 5.0.4
MySQL 4.1.12
and WordPress 1.5.1.3

The problem all originates from MySQL 4.1

version 4.1 MySQL supports different language encodings

problem : “Client” encoding language and the “Server” encoding language.

The “Client” was set to Latin-1 encoding
The “Server” was set to UTF-8

“MySQL tries to translate from one language to the other when it puts the information in its Database. The problem is, my WordPress encoding already was UTF-8. So MySQL basically took UTF-8 encoded text (from WordPress) and treated it as Latin-1 encoded text and tried to convert it to UTF-8. Doing that, some characters where fine but more complex ones where not…

To solve this problem, you have to tell MySQL to treat all the stuff from WordPress as UTF-8 stuff.

First open the file: wordpress\wp-includes\wp-db.php

Find line 56, it should read as this:
$this->select($dbname);

Go to the beginning of the line and punch “enter” to make it move one line down and leave a blank line on line 56.

Then place this line at line 56:
$this->query(“SET NAMES ‘utf8′”);

Then your lines should look like this:
56 $this->query(“SET NAMES ‘utf8′”);
57 $this->select($dbname);

“now have a wordpress that can display and retain text in any language your computer can write in :)

One final note, your Database must be a UTF-8 Database and your WordPress encoding must be UTF-8 also. For wordpress, you can find this in Options/Reading.

Japanese Characters not displaying right!

The patch we found that seems to have worked for some people but not for others was to add the line $this->query (“SET NAMES ‘utf8′”); after line 43 in wp-db.php.

http://wordpress.org/support/topic/48459?replies=6

PHP, MySQL 4.1 and UTF-8

Character Encoding + Transformation

•October 9, 2006 • Leave a Comment

After the damage has occured, the best way, it seems, to clean this up is to run multiple SQL queries in the phpmyadmin console emulating find/replace on the wp_posts table:

UPDATE wp_posts SET post_content = replace(post_content, “bad”, “good”)

Gestion des accents français

1/ exporter sous MySQL dans le bon encodage (sous wordpress, généralement UTF-8).

2/ encodage correct des accents dans les fichiers :

wp_posts, wp_comments, link_categories etc

update wp_posts set post_title=replace(post_title,“é”,“é”);
update wp_posts set post_title=replace(post_title,“Ô,“à”);
update wp_posts set post_title=replace(post_title,“ઔ,“ê”);
update wp_posts set post_title=replace(post_title,“à´”,“ô”);
update wp_posts set post_title=replace(post_title,“࢔,“â”);
update wp_posts set post_title=replace(post_title,“ਔ,“è”);
update wp_posts set post_title=replace(post_title,“௔,“ï”);
update wp_posts set post_title=replace(post_title,“à®”,“î”);
update wp_posts set post_title=replace(post_title,“à©”,“é”);
update wp_posts set post_title=replace(post_title,“à»”,“û”);
update wp_posts set post_title=replace(post_title,“à§”,“ç”);

update wp_posts set post_content=replace(post_content,“é”,“é”);
update wp_posts set post_content=replace(post_content,“Ô,“à”);
update wp_posts set post_content=replace(post_content,“ઔ,“ê”);
update wp_posts set post_content=replace(post_content,“à´”,“ô”);
update wp_posts set post_content=replace(post_content,“࢔,“â”);
update wp_posts set post_content=replace(post_content,“ਔ,“è”);
update wp_posts set post_content=replace(post_content,“௔,“ï”);
update wp_posts set post_content=replace(post_content,“à®”,“î”);
update wp_posts set post_content=replace(post_content,“à©”,“é”);
update wp_posts set post_content=replace(post_content,“à»”,“û”);
update wp_posts set post_content=replace(post_content,“à§”,“ç”);

migration : http://codex.wordpress.org/Moving_WordPress (english)

page en français : Migration wordpress un guide pas à pas pour votre migration. (revolunet)

Transition vers WordPress 2.0.4 et transformation d’une base de données iso-8859-15 au format UTF-8 Wireless

Redirection

Redirection par un fichier .htaccess à la racine du blog sur xxx.domaine.fr/wordpress :

RedirectMatch permanent /wordpress/(.*) http://newsite.com/$1

WordPress 2.0 Upgrade Problems: Character Encoding + Transformation

Blogs Imported (categories)

AJAHT

•October 1, 2006 • Leave a Comment

What’s in a name? That which we call a rose
By any other word would smell as sweet
.”

Romeo and Juliet (II, ii, 1-2)

Introducing AJAHT Rod Divilbiss 12/06/2006