INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

How do I make this a link to related posts?

How do I make this a link to related posts?

(OP)
Hello again,

I was going to put this one in the PHP forum but I think it's WP specific. I'd like to be able to create a link to a special field, so that when it is clicked all pages with the special field are listed. The code is thus:

CODE

      
<?php
  $key = "country";
  $value = get_post_meta($post->ID, $key, true);
  if ($value != "") echo "Country: ".$value." | ";
?>

There is a page on the wordpress codex page that talks about creating queries with special fields: http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query. It's way beyond my ken - does it have to be  this complicated?

RE: How do I make this a link to related posts?

you can do this one of two ways.

1. either change the select query and use a normal loop;
2. or use a standard select query and modify the loop with a condition. at first glance I would use the following as conditional code

CODE

$value = get_post_meta($post->ID, 'country', true);
if (!empty($value)) { echo "Country: $value |";}

i.e. test for empty rather than a zero length string.

RE: How do I make this a link to related posts?

(OP)
Hi J,

Thanks for your response. This is all a bit beyond my ken so I think I need to go and read that article I referred to above. I'll come back when I'm a bit clearer on the subject...

RE: How do I make this a link to related posts?

(OP)
OK, after a cursory glance at that article there are a couple of things I am uncertain of:

1. In my example http://www.followtheboat.com/index.php/?p=311 you can see my three custom fields in the side bar under the log book: UK, East Coast, Levington. The keys for these are Country, Region, Location. These three are links that create the recordset referred to in the article. Clicking on link 'UK', for example, is retrieving the recordset for all articles attributed with the key 'UK'. But how is that link created? What is the code that you wrap around the key 'Country' so that it displays a clickable link displayed as 'UK'?

2. Secondly in the example on the WP website I alluded to in my original post it appears to be calling a key of 'tag' and a value of 'email', so it is already predifining the value. That's drilling down one level too far for me. I just want to call all records with the key 'country', not a value of 'UK'. How would the code differ in this instance?

RE: How do I make this a link to related posts?

i'm not really following you.  can i try to play back what you're asking:

1. you have created some custom fields on certain posts.
2. the fields follow the normal key=>value concept.
3. the custom data displays nicely on your posts
4. you want to make the custom data displays into clickable links
5. when a link is clicked you want to filter NOT by the value of the metafield but simply by whether or not a post HAS the meta-data key irrespective of whether the key has any value.

please confirm or clarify.

RE: How do I make this a link to related posts?

(OP)
Hi J,

My apologies if my explanation is poor. You are right on all points except the last one,  I think. As an example, using my link above: if the user clicks on the link 'UK' the archive.php(?) page will load, producing a list of excerpts of  all articles tagged 'UK'. (I'm assuming it's archive.php but perhaps it is a customised version of page.php. Whatever...)

So I've managed your points from 1-3 ok. Now I need to make them links for the user to click on to produce the filtered list.

RE: How do I make this a link to related posts?

ok.

it's a non-trivial solution because you are wanting to use custom fields in a manner more akin to tags/categories.  

it will require a plugin and some additions to your template.  if I have 15 mins i'll post some code for you to test.
 

RE: How do I make this a link to related posts?

(OP)
Thank you.

RE: How do I make this a link to related posts?

here you go

this assumes you have a search.php template.  if you don't then change the template variable.

install this as a plugin and activate it.  then you need to plonk the meta info widget into your post template (you can do this in the display->widget page.  the meta-info will only dispay in single post pages so you can add the widget without concern.

the plugin makes each metainfo clickable. the click gets passed to the search functionality in wp which then gets interrupted by the plugin and adapted for use with custom fields.  the resultant database query then gets passed back to the_loop to be used as normal. assuming you use the search template, it will display a list of post titles.  if you use another template then the defaults for that template will be used.

warning: i have not tested this at all. bit strapped for time at the moment so i've pretty much just typed it in to the editor.  it should not cause anything to go pop but it might not work either...  let me know either way and i will try to fix.

CODE

<?php
/*
Plugin Name: Custom Field Search Plugin
Plugin URI:
Description: This widget allows searching via a custom field
Author: Justin Adie
Version: 0.1.0
Author URI: http://rathercurious.net
*/

/**
 * plugin to allow searching via a custom field.
 * adapted from http://guff.szub.net/source/search-custom.php
 */
class customFieldsFilter{
    
    private $template = 'archive.php'; // change this to another template file if you want
    
    public function __construct(){
        $this->addFilters();
        
    }
    
    private function addFilters(){
        //make the post-meta searchable
        add_filter('posts_join', array($this, 'addJoin'));
        //construct the search query
        add_filter('posts_where', array($this, 'addWhere'));
        //allow custom templates here or force search.php
        add_filter('search_template', array($this, 'forceTemplate'));
        //make the search query display nicely in the template
        add_filter('the_search_query', array($this, 'searchQuery'));
        add_action ('plugins_loaded', array($this, 'registerWidget'));
    }
    
    private function registerWidget(){
        register_sidebar_widget("Meta Info", array($this, "widgetDisplay"));    
    }
    
    private function addJoin($join){
        if ($this->needy()){
            global $wpdb;
            $join = " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
            return $join;
        } else {
            return $join;
        }
    }

    private function addWhere($where){
        if ($this->needy() ){
            global $wp_query;
            global $wpdb;    
            $where = " AND $wpdb->postmeta.meta_key=%s AND $wpdb->postmeta.meta_value=%s AND post_type=%s AND post_status=%s ";
            $where = $wpdb->prepare($where, $_GET['metaFilterKey'], $wp_query['s'], 'post', 'publish');
            return $where;
        } else {
            return $where;
        }
    }
    
    private function needy(){
        if (is_search() && (!empty($_GET['metaFilterKey']))){
            return true;
        } else {
            return false;
        }
    }
    
    private function forceTemplate($template){
        //use archive.php
        if ($this->needy()){
            if (file_exists(TEMPLATEPATH . "/$this->template")){
                return TEMPLATEPATH . "/$this->template";
            } else {
                return $template;
            }
        } else {
            return $template;
        }
    }    
    private function searchQuery($query){
        if ($this->needy()){
            return "$query in {$_GET[metaFilterKey]} ";
        } else {
            return $query;
        }
    }
    
    public function widgetDisplay($args){
        if (!is_single()){
            echo '';
            return;
        } else {
            extract($args);
            $meta = get_post_custom();
            $url = bloginfo('url');
            $liTemplate = <<<HTML
                
                <li class="post-meta-key"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></li>
HTML;
            $ulTemplate =  <<<HTML
    <div id="meta-links" class="post-meta">
        <ul>
            %s
        </ul>
    </div>
HTML;

            $links = '';
            foreach($meta as $key=>$value){
                $links .= sprintf($liTemplate, urlencode($value), urlencode($key), $value);
            }
            $text = sprintf($ulTemplate, $links);
        //output the widget
            echo <<<HTML
$before_widget
$before_title
Meta Info:
$after_title
{$this->aph}
$after_widget
HTML;
        } //end if single
    } //end method
}//end class

//start the plugin
$customFieldsFilter = new customFieldsFilter();
?>

RE: How do I make this a link to related posts?

(OP)
Hi Justin,

Thanks for your time. I installed the plug-in but received this error message after installing the plug-in (message appears at the top of the plug-in page):

CODE

Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'customFieldsFilter::registerWidget' was given in E:\domains\f\followtheboat.com\user\htdocs\wp-includes\plugin.php on line 339

RE: How do I make this a link to related posts?

mea culpa. give me 2 mins and i will test it properly.

RE: How do I make this a link to related posts?

that was a bit of a brain fart.

revised code follows and is tested.
i have also implemented a non widget method of outputting the meta info.  just add this into your template where you want the list to be output.

CODE

$customFieldsFilter->displayMetaText();

the whole code

CODE

<?php
/*
Plugin Name: Custom Field Search Plugin
Plugin URI:
Description: This widget allows searching via a custom field
Author: Justin Adie
Version: 0.1.0
Author URI: http://rathercurious.net
*/

/**
 * plugin to allow searching via a custom field.
 * adapted from http://guff.szub.net/source/search-custom.php
 */
class customFieldsFilter{
    
    private $template = 'archive.php'; // change this to another template file if you want
    
    public function __construct(){
        $this->addFilters();
        
    }
    
    private function addFilters(){
        //make the post-meta searchable
        add_filter('posts_join', array($this, 'addJoin'));
        //construct the search query
        add_filter('posts_where', array($this, 'addWhere'));
        //allow custom templates here or force search.php
        add_filter('search_template', array($this, 'forceTemplate'));
        //make the search query display nicely in the template
        add_filter('the_search_query', array($this, 'searchQuery'));
        add_action ('plugins_loaded', array($this, 'registerWidget'));
    }
    
    public function registerWidget(){
        register_sidebar_widget("Meta Info", array($this, "widgetDisplay"));    
    }
    
    public function addJoin($join){
        if ($this->needy()){
            global $wpdb;
            $join = " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
            return $join;
        } else {
            return $join;
        }
    }

    public function addWhere($where){
        if ($this->needy() ){
            global $wp_query;
            global $wpdb;    
            $where = " AND $wpdb->postmeta.meta_key=%s AND $wpdb->postmeta.meta_value=%s AND post_type=%s AND post_status=%s ";
            $where = $wpdb->prepare($where, $_GET['metaFilterKey'], $wp_query->query_vars['s'], 'post', 'publish');
            return $where;
        } else {
            return $where;
        }
    }
    
    private function needy(){
        if (is_search() && (!empty($_GET['metaFilterKey']))){
            return true;
        } else {
            return false;
        }
    }
    
    public function forceTemplate($template){
        //use archive.php
        if ($this->needy()){
            if (file_exists(TEMPLATEPATH . "/$this->template")){
                return TEMPLATEPATH . "/$this->template";
            } else {
                return $template;
            }
        } else {
            return $template;
        }
    }    
    public function searchQuery($query){
        if ($this->needy()){
            return "$query in {$_GET[metaFilterKey]} ";
        } else {
            return $query;
        }
    }
    
    public function displayMetaText(){
        echo $this->getMetaText();
    }
    
    private function getMetaText(){
        $meta = get_post_custom();
        $url = get_bloginfo('url');
            $liTemplate = <<<HTML
                
                <li class="post-meta-key"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></li>
HTML;
            $ulTemplate =  <<<HTML
    <div id="meta-links" class="post-meta">
        <ul>
            %s
        </ul>
    </div>
HTML;

            $links = '';
            
            
            foreach($meta as $key=>$value){
                if (substr($key, 0, 1) == '_'){
                    continue;
                }
                $links .= sprintf($liTemplate, urlencode($value[0]), urlencode($key), $value[0]);
            }
            
            $text = sprintf($ulTemplate, $links);
            return $text;
    }
    public function widgetDisplay($args){
        if (!is_single()){
            echo '';
            return;
        } else {
            extract($args);
            $meta = get_post_custom();
            
        //output the widget
            echo <<<HTML
$before_widget
$before_title
Meta Info:
$after_title
{$this->getMetaText()}
$after_widget
HTML;
        } //end if single
    } //end method
}//end class

//start the plugin
$customFieldsFilter = new customFieldsFilter();
?>

RE: How do I make this a link to related posts?

(OP)
Hi,

I've placed the code

CODE

<?php $customFieldsFilter->displayMetaText();?>  
in my sidebar, which returns the following error:

CODE

Fatal error: Call to a member function displayMetaText() on a non-object in E:\domains\f\followtheboat.com\user\htdocs\wp-content\themes\followtheboat\sidebar_post.php on line 43
I'm unclear - is there anywhere within the plug-in section where i can configure this, or does it automatically make every special field a link? I can't see anywhere under Settings where I can switch on/off custom fields (not that that is what I was after you understand).

RE: How do I make this a link to related posts?

no configuration options no. the code does exclude keys that begin within an underscore though.

the code will not work that way in the sidebar.  Use the widget method if you want to add the links into the sidebar. Use the displayMetaText() method if you want to display the links in the main post screen.  

there is a way around this if you really need.   

RE: How do I make this a link to related posts?

I should add that if you want a defined set of custom Fields to be picked up then it's pretty easy to add to the code.  
change line 113 from this

CODE

if (substr($key, 0, 1) == '_'){

to the following

CODE

if ( !in_array($key, $this->customFields)){

then at the top of the class add this

CODE

private $customFields = array('country', 'whatever', 'else');

RE: How do I make this a link to related posts?

(OP)
Er, how do I use the widget method? I've avoided using widgets completely. When I first started with WP I found using widgets inflexible so I've ended up hard-coding all side-bar content.

RE: How do I make this a link to related posts?

(OP)
Don't answer that last post, Justin, I'm a big boy, I'm sure I can work it out! I'll get back to you in a bit (gotta break for dinner). Thanks for your help so far...

RE: How do I make this a link to related posts?

oh.

if your theme is widget enabled you just go to design->widgets in the admin menu, click add by Meta Info (the name of the filter) and then save.  

that's all.

if you want to use the hardcoded method just add this to the top of your sidebar.php file

CODE

<?php global $customFieldsFilter; ?>

RE: How do I make this a link to related posts?

(OP)
OK, just before I break off I managed to get the special fields to display with the links. You can see them here:

http://www.followtheboat.com/index.php?p=57

The sidebar is a little messy as I'm working on other stuff but you can see your linked special fields half way down.

What I'd like to do is format them and switch on/off special fields. All the data you see displayed is all the data held against this one post. Most of these special fields appear in the log-book image at the top of the sidebar, but I'd like to format the fields country/region/location as per underneath that log book (i.e.: Turkey » Caria » Bodrum).

RE: How do I make this a link to related posts?

create the $customFields array as set out above. make sure that the array items are in the order you want them to display. then swap out this method.

CODE

    private function getMetaText(){
        $meta = get_post_custom();
        $url = get_bloginfo('url');
        $template = <<<HTML
                
                <span class="post-meta"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></span>
HTML;

        $links = '';
                
        foreach($this->customFields as $cF){
            if (isset($meta[$cF])){
            $links[]= sprintf($liTemplate, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);
        }
        
        return implode (" >>> ", $links);
    }

RE: How do I make this a link to related posts?

(OP)
Hello again,

Let me confirm the following:

1. We are not using the sidebar widget, everything is hard coded.
2. I've added

CODE

<?php global $customFieldsFilter; ?>
to the top of my sidebar_post.php page. Do I then add

CODE

$customFieldsFilter->displayMetaText();
where I want my special fields to appear?
3. After copying the code from above I've added

CODE

private $customFields = array('country', 'region', 'location');
to line 18.
4. At line 113 I've swapped the code over to read

CODE

if ( !in_array($key, $this->customFields)){
At this point I stopped and tested it and it is returning an error:

Quote:

Fatal error: Call to a member function displayMetaText() on a non-object in E:\domains\f\followtheboat.com\user\htdocs\wp-content\themes\followtheboat\sidebar_post.php on line 89
.
I think I'm getting confused with what I am inserting in the sidebar, now that I am not using the widget. If you could advise on this then I'll tackle the changes to the layout you suggested. Thank you very much.

RE: How do I make this a link to related posts?

1. not sure that's a great idea, but your choice.

2. yes. you use

CODE

$customFieldsFilter->displayMetaText();
to display the meta info.  But see below.

3. yes. fine. so long as the custom fields are also in lower case.

4. no. use the code i last posted (the getMetaText method) instead (@16:18 yesterday). just replace one with the other.

the error that you are getting indicates that $customFieldsFilter is not in the same variable scope as whatever is happening in sidebar-post.php (which is usually included by get_sidebar()). hence the requirement for using the global keyword.   A sure fire way of making it work (but an ugly way) is to use this code to display the custom links

CODE

$GLOBALS['customFieldsFilter']->displayMetaText();

this is, stylistically, a bit ugly, but should work. to be prettier i would need to see the code of sidebar-post.php in all its glory.



 

RE: How do I make this a link to related posts?

(OP)
Good morning Justin,

I hope you are well. I've managed to get the links to appear WHERE I want, so I think sidebar is sorted, but I'm still getting confused on what I am taking out of the make-links code and how I only display country, region, location.

Looking at your post 16:18 it looks very similar to lines 94 to 121 or 94 to 117. I've tried pasting over these lines but either option returns an error. Am I taking all of the code from post 16:18 and pasting it over just line 113? That returns an error as well. I think with all the to-ing and fro-ing I'm getting muddled.

If you go to http://www.followtheboat.com/index.php?p=57 you see the result of adding the two lines of code in the sidebar (as per below) and using your original code as per post 11:00, with line 18 added (though that's not making any difference).

What would you suggest is the best option? Why should I use the sidebar widget? Does this not make it more difficult to style? You can see from the above link that the country, region, location links sit within a styled section underneath the log-book image.

CODE

<?php global $customFieldsFilter; ?>
<div id="sidebar2">
  <p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>
     
  <div class="logbook">  
    <div class="logbookpositionl">
      <?php the_time('d F, Y') ?><br><br>
      <?php
        $key = "leg";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br><br>
      <?php
        $key = "lat";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br>
      <?php
        $key = "lon";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?>
            
    </div>
    <div class="logbookpositionr">
      <?php
        $key = "vessel";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Vessel: ".$value;
        ?><br><br>
      <?php
        $key = "distance";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value . " nautical miles";
        ?><br><br>      
      <?php
        $key = "weather";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Weather: ".$value;
        ?>        
    </div>
  </div>
  
<?php $customFieldsFilter->displayMetaText(); ?>

      <div class="tags">
      <div class="tagicon">        
         <img src="<?php bloginfo('template_directory'); ?>/images/minimap.gif" height="17" width="17" alt="Location" title="Location">
      </div>
      <div class="taglinks">      <?php
        $key = "country";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "region";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "location";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value;
        ?>
        
        <?php if (have_posts()) : while (have_posts()) : the_post(); ?>    </div>
    </div>
        
      <div class="tags">
      <div class="tagicon">
        <img src="<?php bloginfo('template_directory'); ?>/images/minicat.gif" height="17" width="17" alt="Category" title="Category">
      </div>
      <div class="taglinks"><?php the_category(', ') ?></div>
    </div>
    <div class="tags">
      <div class="tagicon2">
        <img src="<?php bloginfo('template_directory'); ?>/images/tag.gif" height="17" width="17" alt="Tags" title="Tags"/>
      </div>
      <div class="taglinks"><?php the_tags('); ?></div>
    </div>       
    <div class="tagbuffer">&nbsp;</div>
    <?php endwhile; else: ?>
            <p>Sorry, no posts matched your criteria.</p>
            <?php endif; ?>
        
   <div class="side-heading"><img src="<?php bloginfo('template_directory');?>/images/side-related.gif" width="250" height="32"></div>
   <div class="similarposts"><?php similar_posts(); ?>  </div>
 
       

            
  <div id="side-cat"><p>&nbsp;</p><p>&nbsp;</p>
      <ul><li ><?php wp_list_categories('sort_column=name&optioncount=1&hierarchical=0&title_li=&show_count=1&hide_empty=1'); ?></li></ul>
  </div>        
  <div class="googlecontainer">
    <div class="gogglebutton"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 200x200, created 14/12/08 */
        google_ad_slot = "1228560132";
        google_ad_width = 200;
        google_ad_height = 200;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>


  <div id="archive">
    <div class="archiveposition">  <?php wp_get_archives('type=monthly'); ?><p>&nbsp;</p><p>&nbsp;</p></div>
  </div>
  
    <div class="googlecontainer">
    <div class="widesky"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 160x600, created 14/12/08 */
        google_ad_slot = "7364380115";
        google_ad_width = 160;
        google_ad_height = 600;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>

</div>

RE: How do I make this a link to related posts?

ok

in answer to your question as to sidebar usage: my retort was based primarily on maintaining flexibility in the interface and across theme refreshes. using a widget is a simple matter of enabling it.  you can style the widget completely as you wish through editing the $args that get extracted in the widget display code.  you can also, of course, always style in css.  there is nothing _wrong_ with hard-coding if you're comfortable doing so.

if you wanted, we could adjust the code so that it retrieves whatever custom field you plugged in. and made it nice and clickable. then you could replace all the conditionals in your code.  let me know.

in your display code edit this as shown

CODE

<?php $GLOBALS['customFieldsFilter']->displayMetaText(); ?>

and i have reposted the whole code block of the plugin for clarity

CODE

<?php
/*
Plugin Name: Custom Field Search Plugin
Plugin URI:
Description: This widget allows searching via a custom field
Author: Justin Adie
Version: 0.1.0
Author URI: http://rathercurious.net
*/

/**
 * plugin to allow searching via a custom field.
 * adapted from http://guff.szub.net/source/search-custom.php
 */
class customFieldsFilter{
    
    private $template = 'archive.php'; // change this to another template file if you want
    private $customFields = array('country', 'region', 'location');
    
    public function __construct(){
        $this->addFilters();
        
    }
    
    private function addFilters(){
        //make the post-meta searchable
        add_filter('posts_join', array($this, 'addJoin'));
        //construct the search query
        add_filter('posts_where', array($this, 'addWhere'));
        //allow custom templates here or force search.php
        add_filter('search_template', array($this, 'forceTemplate'));
        //make the search query display nicely in the template
        add_filter('the_search_query', array($this, 'searchQuery'));
        add_action ('plugins_loaded', array($this, 'registerWidget'));
    }
    
    public function registerWidget(){
        register_sidebar_widget("Meta Info", array($this, "widgetDisplay"));    
    }
    
    public function addJoin($join){
        if ($this->needy()){
            global $wpdb;
            $join = " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
            return $join;
        } else {
            return $join;
        }
    }

    public function addWhere($where){
        if ($this->needy() ){
            global $wp_query;
            global $wpdb;    
            $where = " AND $wpdb->postmeta.meta_key=%s AND $wpdb->postmeta.meta_value=%s AND post_type=%s AND post_status=%s ";
            $where = $wpdb->prepare($where, $_GET['metaFilterKey'], $wp_query->query_vars['s'], 'post', 'publish');
            return $where;
        } else {
            return $where;
        }
    }
    
    private function needy(){
        if (is_search() && (!empty($_GET['metaFilterKey']))){
            return true;
        } else {
            return false;
        }
    }
    
    public function forceTemplate($template){
        //use archive.php
        if ($this->needy()){
            if (file_exists(TEMPLATEPATH . "/$this->template")){
                return TEMPLATEPATH . "/$this->template";
            } else {
                return $template;
            }
        } else {
            return $template;
        }
    }    
    public function searchQuery($query){
        if ($this->needy()){
            return "$query in {$_GET[metaFilterKey]} ";
        } else {
            return $query;
        }
    }
    
    public function displayMetaText(){
        echo $this->getMetaText();
    }
    
    private function getMetaText(){
        $meta = get_post_custom();
        $url = get_bloginfo('url');
        $template = <<<HTML
                
                <span class="post-meta"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></span>
HTML;

        $links = '';
                
        foreach($this->customFields as $cF){
            if (isset($meta[$cF])){
            $links[]= sprintf($liTemplate, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);
        }
        
        return implode (" >>> ", $links);
    }

    public function widgetDisplay($args){
        if (!is_single()){
            echo '';
            return;
        } else {
            extract($args);
            $meta = get_post_custom();
            
        //output the widget
            echo <<<HTML
$before_widget
$before_title
Meta Info:
$after_title
{$this->getMetaText()}
$after_widget
HTML;
        } //end if single
    } //end method
}//end class

//start the plugin
$customFieldsFilter = new customFieldsFilter();
?>
 

RE: How do I make this a link to related posts?

(OP)
Sorry Justin, what do you mean 'edit this as shown'? What am I editing and where am I placing it? Is the widget switched on? Am I calling the widget again in the sidebar? If not how has the sidebar code changed from what I posted above?

RE: How do I make this a link to related posts?

the coloured red bits show the edits.  
the widget is switched off as this provides you with hardcoded solution.

the change in your sidebar is from

CODE

<?php $customFieldsFilter->displayMetaText(); ?>
to

CODE

<?php $GLOBALS['customFieldsFilter']->displayMetaText(); ?>

i have a sneaky feeling that this will need to be inside the loop but then i also assume that the whole sidebar is inside the loop for a single post.  anyway. try it out.

RE: How do I make this a link to related posts?

btw, i'm not a fan of the comment CAPTCHA that you're using.  why not use akismet instead?  

if you check out my site at rathercurious.net i have explained a robust alternative to image and similar types of CAPTCHA that requires no user interaction.

RE: How do I make this a link to related posts?

(OP)
Cheers Justin. I only added that in yesterday but I have akismet running anyway. I'll check your website out again in a bit.

Apologies for slow response - they've just switched off the router here at the marina/hotel so I'm now having to use the marina next door ;)

RE: How do I make this a link to related posts?

(OP)
OK, so we've now got the list where we want it (ignore the styling for the time being). Now how do I just display the three custom fields? I've have thought I'd modify the line thus:

CODE

<?php $GLOBALS['customFieldsFilter']->displayMetaText('country', 'region', 'location'); ?>

...but it displays all the fields.

RE: How do I make this a link to related posts?

nope. just the empty brackets.

the three custom fields are limited by the loop in getMetaText(). just make sure you are using the new version of that method as posted above.

RE: How do I make this a link to related posts?

(OP)
Using the code as per post 6:14. Reverted back to

CODE

<?php $GLOBALS['customFieldsFilter']->displayMetaText(); ?>
.

It tripped up on line 113, the widget call. At that point I couldn't go into admin mode on my site so I've had to revert back to the older code in order to get in, and then deactivate the plugin.

What I'll do it post this message, and then do the above again so you can see what's happening.

RE: How do I make this a link to related posts?

(OP)
So at the moment the plug-in is disabled and it is tripping up on our displayMetaText:

Quote:

Fatal error: Call to a member function displayMetaText() on a non-object in E:\domains\f\followtheboat.com\user\htdocs\wp-content\themes\followtheboat\sidebar_post.php on line 51

I will now enable the plug-in

RE: How do I make this a link to related posts?

(OP)
And now I can't activate the plugin due to that call to the widget, line 113:

CODE

Parse error: syntax error, unexpected T_PUBLIC in E:\domains\f\followtheboat.com\user\htdocs\wp-content\plugins\make-custom-fields-links.php on line 113

RE: How do I make this a link to related posts?

the error that i see is the variable scope again. i cannot reproduce this on my servers so it is difficult to assist. the variable should be in the global scope from where it is created in the plugin handler.  using the $GLOBALS superglobal should allow it be accessible to the sidebar.

one error spotted. please change this line

CODE

 $links[]= sprintf($liTemplate, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);
to

CODE

 $links[]= sprintf($template, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);

RE: How do I make this a link to related posts?

(OP)
Hello again,

I think this needs a fresh head. I've now got to start preparing for a sail over to Rhodes for Christmas (leave tomorrow) and I need to concentrate on this 110%. What say we leave this for a week? I would like to thank you very much for all your help, Justin, it's very much appreciated. I will now post the code, completely, as it stands, which produces the error message

Quote:

Fatal error: Call to a member function displayMetaText() on a non-object in E:\domains\f\followtheboat.com\user\htdocs\wp-content\themes\followtheboat\sidebar_post.php on line 44

So, my current code in two .php pages:

1. sidebar_page.php, stored in the root of my theme

CODE

<div id="sidebar2">
  <p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>
     
  <div class="logbook">  
    <div class="logbookpositionl">
      <?php the_time('d F, Y') ?><br><br>
      <?php
        $key = "leg";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br><br>
      <?php
        $key = "lat";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br>
      <?php
        $key = "lon";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?>
            
    </div>
    <div class="logbookpositionr">
      <?php
        $key = "vessel";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Vessel: ".$value;
        ?><br><br>
      <?php
        $key = "distance";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value . " nautical miles";
        ?><br><br>      
      <?php
        $key = "weather";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Weather: ".$value;
        ?>        
    </div>
  </div>
  
<?php $GLOBALS['customFieldsFilter']->displayMetaText(); ?>

      <div class="tags">
      <div class="tagicon">        
         <img src="<?php bloginfo('template_directory'); ?>/images/minimap.gif" height="17" width="17" alt="Location" title="Location">
      </div>
      <div class="taglinks">      <?php
        $key = "country";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "region";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "location";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value;
        ?>
        
        <?php if (have_posts()) : while (have_posts()) : the_post(); ?>    </div>
    </div>
        
      <div class="tags">
      <div class="tagicon">
        <img src="<?php bloginfo('template_directory'); ?>/images/minicat.gif" height="17" width="17" alt="Category" title="Category">
      </div>
      <div class="taglinks"><?php the_category(', ') ?></div>
    </div>
    <div class="tags">
      <div class="tagicon2">
        <img src="<?php bloginfo('template_directory'); ?>/images/tag.gif" height="17" width="17" alt="Tags" title="Tags"/>
      </div>
      <div class="taglinks"><?php the_tags(''); ?></div>
    </div>       
    <div class="tagbuffer">&nbsp;</div>
    <?php endwhile; else: ?>
            <p>Sorry, no posts matched your criteria.</p>
            <?php endif; ?>
        
   <div class="side-heading"><img src="<?php bloginfo('template_directory');?>/images/side-related.gif" width="250" height="32"></div>
   <div class="similarposts"><?php similar_posts(); ?>  </div>
 
       

            
  <div id="side-cat"><p>&nbsp;</p><p>&nbsp;</p>
      <ul><li ><?php wp_list_categories('sort_column=name&optioncount=1&hierarchical=0&title_li=&show_count=1&hide_empty=1'); ?></li></ul>
  </div>        
  <div class="googlecontainer">
    <div class="gogglebutton"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 200x200, created 14/12/08 */
        google_ad_slot = "1228560132";
        google_ad_width = 200;
        google_ad_height = 200;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>


  <div id="archive">
    <div class="archiveposition">  <?php wp_get_archives('type=monthly'); ?><p>&nbsp;</p><p>&nbsp;</p></div>
  </div>
  
    <div class="googlecontainer">
    <div class="widesky"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 160x600, created 14/12/08 */
        google_ad_slot = "7364380115";
        google_ad_width = 160;
        google_ad_height = 600;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>

</div>

2. make-custom-field-links.php, stored in the plugin dir

CODE

<?php
/*
Plugin Name: Custom Field Search Plugin
Plugin URI:
Description: This widget allows searching via a custom field
Author: Justin Adie
Version: 0.1.0
Author URI: http://rathercurious.net
*/

/**
 * plugin to allow searching via a custom field.
 * adapted from http://guff.szub.net/source/search-custom.php
 */
class customFieldsFilter{
    
    private $template = 'archive.php'; // change this to another template file if you want
    private $customFields = array('country', 'region', 'location');
    
    public function __construct(){
        $this->addFilters();
        
    }
    
    private function addFilters(){
        //make the post-meta searchable
        add_filter('posts_join', array($this, 'addJoin'));
        //construct the search query
        add_filter('posts_where', array($this, 'addWhere'));
        //allow custom templates here or force search.php
        add_filter('search_template', array($this, 'forceTemplate'));
        //make the search query display nicely in the template
        add_filter('the_search_query', array($this, 'searchQuery'));
        add_action ('plugins_loaded', array($this, 'registerWidget'));
    }
    
    public function registerWidget(){
        register_sidebar_widget("Meta Info", array($this, "widgetDisplay"));    
    }
    
    public function addJoin($join){
        if ($this->needy()){
            global $wpdb;
            $join = " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
            return $join;
        } else {
            return $join;
        }
    }

    public function addWhere($where){
        if ($this->needy() ){
            global $wp_query;
            global $wpdb;    
            $where = " AND $wpdb->postmeta.meta_key=%s AND $wpdb->postmeta.meta_value=%s AND post_type=%s AND post_status=%s ";
            $where = $wpdb->prepare($where, $_GET['metaFilterKey'], $wp_query->query_vars['s'], 'post', 'publish');
            return $where;
        } else {
            return $where;
        }
    }
    
    private function needy(){
        if (is_search() && (!empty($_GET['metaFilterKey']))){
            return true;
        } else {
            return false;
        }
    }
    
    public function forceTemplate($template){
        //use archive.php
        if ($this->needy()){
            if (file_exists(TEMPLATEPATH . "/$this->template")){
                return TEMPLATEPATH . "/$this->template";
            } else {
                return $template;
            }
        } else {
            return $template;
        }
    }    
    public function searchQuery($query){
        if ($this->needy()){
            return "$query in {$_GET[metaFilterKey]} ";
        } else {
            return $query;
        }
    }
    
    public function displayMetaText(){
        echo $this->getMetaText();
    }
    
    private function getMetaText(){
        $meta = get_post_custom();
        $url = get_bloginfo('url');
        $template = <<<HTML
                
                <span class="post-meta"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></span>
HTML;

        $links = '';
                
        foreach($this->customFields as $cF){
            if (isset($meta[$cF])){
             $links[]= sprintf($template, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);
        }
        
        return implode (" >>> ", $links);
    }

    public function widgetDisplay($args){
        if (!is_single()){
            echo '';
            return;
        } else {
            extract($args);
            $meta = get_post_custom();
            
        //output the widget
            echo <<<HTML
$before_widget
$before_title
Meta Info:
$after_title
{$this->getMetaText()}
$after_widget
HTML;
        } //end if single
    } //end method
}//end class

//start the plugin
$customFieldsFilter = new customFieldsFilter();
?>

If we don't chat again before, then a very merry Christmas to you. I look forward to catching up with you again soon.

Kindest regards,

Jamie

RE: How do I make this a link to related posts?

thanks for the wishes, and likewise.

if you want, zip up your theme files and upload them to me here: http://www.adieandco.com/uploads/

i'll fix them for you and post them back.

best of luck for the sail, hope the weather holds.
 

RE: How do I make this a link to related posts?

(OP)
I've just uploaded it, hope it's received ok.  

You should be aware that my theme is based on another theme, modern_era. It bears no resemblance to it though as it's completely re-written (and not always correctly).

Cheers Justin.

RE: How do I make this a link to related posts?

ok. it's done.

CODE --> sidebar-post.php


<div id="sidebar2">
  <p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p>
     
  <div class="logbook">  
    <div class="logbookpositionl">
      <?php the_time('d F, Y') ?><br><br>
      <?php
        $key = "leg";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br><br>
      <?php
        $key = "lat";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?><br>
      <?php
        $key = "lon";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "".$value;
        ?>
            
    </div>
    <div class="logbookpositionr">
      <?php
        $key = "vessel";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Vessel: ".$value;
        ?><br><br>
      <?php
        $key = "distance";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value . " nautical miles";
        ?><br><br>      
      <?php
        $key = "weather";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo "Weather: ".$value;
        ?>        
    </div>
  </div>
  
<?php /*echo "<pre>" . print_r($GLOBALS, true) . "</pre>"; */$GLOBALS['customFieldsFilter']->displayMetaText(); ?>

      <div class="tags">
      <div class="tagicon">        
         <img src="<?php bloginfo('template_directory'); ?>/images/minimap.gif" height="17" width="17" alt="Location" title="Location">
      </div>
      <div class="taglinks">      <?php
        $key = "country";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "region";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value." &raquo; ";
        ?>
    <?php
        $key = "location";
        $value = get_post_meta($post->ID, $key, true);
        if ($value != "") echo $value;
        ?>
        
        <?php if (have_posts()) : while (have_posts()) : the_post(); ?>    </div>
    </div>
        
      <div class="tags">
      <div class="tagicon">
        <img src="<?php bloginfo('template_directory'); ?>/images/minicat.gif" height="17" width="17" alt="Category" title="Category">
      </div>
      <div class="taglinks"><?php the_category(', ') ?></div>
    </div>
    <div class="tags">
      <div class="tagicon2">
        <img src="<?php bloginfo('template_directory'); ?>/images/tag.gif" height="17" width="17" alt="Tags" title="Tags"/>
      </div>
      <div class="taglinks"><?php the_tags(''); ?></div>
    </div>       
    <div class="tagbuffer">&nbsp;</div>
    <?php endwhile; else: ?>
            <p>Sorry, no posts matched your criteria.</p>
            <?php endif; ?>
        
   <div class="side-heading"><img src="<?php bloginfo('template_directory');?>/images/side-related.gif" width="250" height="32"></div>
   <div class="similarposts"><?php similar_posts(); ?>  </div>
 
       

            
  <div id="side-cat"><p>&nbsp;</p><p>&nbsp;</p>
      <ul><li ><?php wp_list_categories('sort_column=name&optioncount=1&hierarchical=0&title_li=&show_count=1&hide_empty=1'); ?></li></ul>
  </div>        
  <div class="googlecontainer">
    <div class="gogglebutton"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 200x200, created 14/12/08 */
        google_ad_slot = "1228560132";
        google_ad_width = 200;
        google_ad_height = 200;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>


  <div id="archive">
    <div class="archiveposition">  <?php wp_get_archives('type=monthly'); ?><p>&nbsp;</p><p>&nbsp;</p></div>
  </div>
  
    <div class="googlecontainer">
    <div class="widesky"><script type="text/javascript"><!--
        google_ad_client = "pub-7290301843408108";
        /* 160x600, created 14/12/08 */
        google_ad_slot = "7364380115";
        google_ad_width = 160;
        google_ad_height = 600;
        //-->
        </script>
        <script type="text/javascript"
        src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
    </div>
  </div>

</div>

CODE --> plugin

<?php
/*
Plugin Name: Custom Field Search Plugin
Plugin URI:
Description: This widget allows searching via a custom field
Author: Justin Adie
Version: 0.1.0
Author URI: http://rathercurious.net
*/

/**
 * plugin to allow searching via a custom field.
 * adapted from http://guff.szub.net/source/search-custom.php
 */
class customFieldsFilter{
    
    private $template = 'archive.php'; // change this to another template file if you want
    private $customFields = array('country', 'region', 'location');
    
    public function __construct(){
        $this->addFilters();
        
    }
    
    private function addFilters(){
        //make the post-meta searchable
        add_filter('posts_join', array($this, 'addJoin'));
        //construct the search query
        add_filter('posts_where', array($this, 'addWhere'));
        //allow custom templates here or force search.php
        add_filter('search_template', array($this, 'forceTemplate'));
        //make the search query display nicely in the template
        add_filter('the_search_query', array($this, 'searchQuery'));
        add_action ('plugins_loaded', array($this, 'registerWidget'));
    }
    
    public function registerWidget(){
        register_sidebar_widget("Meta Info", array($this, "widgetDisplay"));    
    }
    
    public function addJoin($join){
        if ($this->needy()){
            global $wpdb;
            $join = " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
            return $join;
        } else {
            return $join;
        }
    }

    public function addWhere($where){
        if ($this->needy() ){
            global $wp_query;
            global $wpdb;    
            $where = " AND $wpdb->postmeta.meta_key=%s AND $wpdb->postmeta.meta_value=%s AND post_type=%s AND post_status=%s ";
            $where = $wpdb->prepare($where, $_GET['metaFilterKey'], $wp_query->query_vars['s'], 'post', 'publish');
            return $where;
        } else {
            return $where;
        }
    }
    
    private function needy(){
        if (is_search() && (!empty($_GET['metaFilterKey']))){
            return true;
        } else {
            return false;
        }
    }
    
    public function forceTemplate($template){
        //use archive.php
        if ($this->needy()){
            if (file_exists(TEMPLATEPATH . "/$this->template")){
                return TEMPLATEPATH . "/$this->template";
            } else {
                return $template;
            }
        } else {
            return $template;
        }
    }    
    public function searchQuery($query){
        if ($this->needy()){
            return "$query in {$_GET[metaFilterKey]} ";
        } else {
            return $query;
        }
    }
    
    public function displayMetaText(){
        echo $this->getMetaText();
    }
    
    private function getMetaText(){
        $meta = get_post_custom();
        $url = get_bloginfo('url');
        $template = <<<HTML
                
                <span class="post-meta"><a href="{$url}?s=%s&metaFilterKey=%s">%s</a></span>
HTML;

        $links = '';
                
        foreach($this->customFields as $cF){
            if (isset($meta[$cF])){
            $links[]= sprintf($template, urlencode($meta[$cF][0]), urlencode($cF), $meta[$cF][0]);
            }
        }
        
        return implode (" >>> ", $links);
    }

    public function widgetDisplay($args){
        if (!is_single()){
            echo '';
            return;
        } else {
            extract($args);
            $meta = get_post_custom();
            
        //output the widget
            echo <<<HTML
$before_widget
$before_title
Meta Info:
$after_title
{$this->getMetaText()}
$after_widget
HTML;
        } //end if single
    } //end method
}//end class

//start the plugin
$customFieldsFilter = new customFieldsFilter();
?>
 

RE: How do I make this a link to related posts?

(OP)
Hey Justin,

Just a quick one to wish you a happy new year, to thank you and to let you know I've implemented this and it's looking good! New year I'll style it a bit more but in the meantime thank you for your assistance.

Kind regards,

Jamie

RE: How do I make this a link to related posts?

glad to hear you're safe and sound after Rhodes!

happy new year to you and yours

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close