Pages

Thursday, November 8, 2012

Easily get posts with a specific custom field/value on your WordPress blog

Easily get posts with a specific custom field/value on your WordPress blog

 <?php query_posts('meta_key=review_type&meta_value=movie'); ?>  
 <?php if (have_posts()) : ?>  
 <?php while (have_posts()) : the_post(); ?>  

WordPress $post Variable Keys

WordPress $post Variable Keys
Below are the methods of retrieving the information that you are most likely to need.
  • $post–>ID – ID of the current post.
  • $post–>post_category - Retrieves the ID of the post category.
  • $post–>post_parent - ID of the page parent. Useful for creating custom navigational elements.
  • $post–>post_title – Post Title
  • $post–>post_excerpt - Post excerpt
  • $post–>post_content – Retrieves all of the post content, along with any markup.
  • $post–>post_name – Retrieving the slug of a post.
  • $post–>guid – Post Url
  • $post–>post_author – ID of post author post_parent
  • $post–>post_type - Returns the type, page or post.
  • $post–>menu_order - Returns the menu order as set in the post/page editing window. Often menu items are sorted via this value.
  • $post–>post_date - Retrieves the integer timestamp for when the post was published. The output can be customized. See the php.net date manual.
  • $post–>post_modified - Retrieves the integer timestamp for when the post was last modified.
  • $post–>post_status - Retrieves one of five possible posts statuses: publish, private, draft, pending, future.
  • $post–>comment_count - Returns the number of comments, pings, and trackbacks for a given post.
 And here is how to use it

 <?php if (have_posts()) : while (have_posts()) : the_post();  
 //somewhere in the loop  
 $yourvariable = $post->post_content;  
 //do something  
 endwhile; endif; ?>  

Wordpress get posts on basis of name,category,tag

Since we have post name involved here long with category and tag we need to use custom query here which will provide us to search specific posts which contain special text in name and will belong to a particular category and will contain a tag as per requirements

Here is the custom query

I used a get in my search form with normal request parameters

 if (!(empty($_GET['section'])) || !(empty($_GET['article']))) {  
       global $wpdb, $post, $paged, $max_num_pages, $current_date;  
       $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;  
       $post_per_page = intval(get_query_var('posts_per_page'));  
       $offset = ($paged - 1) * $post_per_page;  
       $val = $_GET['s'];  
       $cat = $_GET['category'];  
       $tag = $_GET['tag'];  
 $querystr = "  
   SELECT DISTINCT $wpdb->posts.*  
   FROM $wpdb->posts  
   LEFT JOIN $wpdb->postmeta wpostmeta ON ($wpdb->posts.ID = wpostmeta.post_id)  
   LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)  
   LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)  
     WHERE  
     $wpdb->posts.post_type = 'post'  
     AND $wpdb->posts.post_status='publish'";  
 //Tags and categories were like dropdowns so each time either "0" for no select or tag_id or //category_id or both were sent via GET as url params  
       if($tag > 0 && $cat > 0)  
       {  
         $querystr = $querystr . " AND ($wpdb->posts.post_title like '%$val%' AND ($wpdb->term_taxonomy.taxonomy = 'post_tag'  
       AND $wpdb->term_taxonomy.term_id IN($tag))) OR ($wpdb->posts.post_title like '%$val%' AND ($wpdb->term_taxonomy.taxonomy = 'category'  
       AND $wpdb->term_taxonomy.term_id IN($cat)))";  
       }  
       elseif ($tag > 0) {  
         $querystr = $querystr ." AND $wpdb->posts.post_title like '%$val%' AND ($wpdb->term_taxonomy.taxonomy = 'post_tag'  
       AND $wpdb->term_taxonomy.term_id IN($tag))";  
       }  
       elseif ($cat > 0) {  
               $querystr = $querystr . " AND $wpdb->posts.post_title like '%$val%' AND ($wpdb->term_taxonomy.taxonomy = 'category'  
         AND $wpdb->term_taxonomy.term_id IN($cat))";  
          }  
       $pageposts = $wpdb->get_results($querystr, OBJECT);  
       $querystr = $querystr . " LIMIT " . $offset . ", " . $post_per_page . "; ";  
       $sql_posts_total = $wpdb->get_var("SELECT FOUND_ROWS();");  
       $max_num_pages = ceil($sql_posts_total / $post_per_page);  

 //And can use pagination as
  <?php if ($wp_query->max_num_pages > 1) : ?>  
           <nav id="<?php echo $nav_id; ?>">  
             <div class="nav-previous"><?php next_posts_link(__('<span class="meta-nav">&larr;</span> Older posts', 'old')); ?></div>  
             <div class="nav-next"><?php previous_posts_link(__('Newer posts <span class="meta-nav">&rarr;</span>', 'next')); ?></div>  
           </nav>  
   <?php endif; ?>   


This is one way out...

Other way out is to put this filter in your functions.php

 add_filter('posts_where','wpse_posts_where', 10, 2 );  
 function wpse_posts_where( $where, &$wp_query )  
 {  
   global $wpdb;  
   if ( $wpse_title = $wp_query->get( 'wpse_title' ) ) {  
     $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $wpse_title ) ) . '%\'';  
   }  
   return $where;  
 }  


and then make a call to

 <?php if(!(empty($_GET['category'])) || !(empty($_GET['tag'])))  
 {  
   $val=$_GET['s'];  
   $cat=$_GET['category'];  
   $tag=$_GET['tag'];  
      global $query_string;  
      $qstr= $query_string."wpse_title=$val";  
      $args['wpse_title']=$val;  
      if($cat>0)  
      {  
           $args['category__and']=$cat;  
           $qstr=$qstr."&cat=$cat";  
      }  
      if ($tag>0)  
   {  
           $args['tag__in'] = $tag;  
           $qstr=$qstr."&tag=$tag";  
   }  
      query_posts($args);  
      query_posts($qstr);  
 ?>  


They both work how ever in later case youcan either make via name and category or name and tag

If you try to search via name category and tag you will end up getting a response which contains all the posts of that category..so I preffered using a custom query as it suited me

Tuesday, November 6, 2012

.htacess rewrite rule translation example

RewriteRule  ^builder/([0-9]*)/([0-9]*)/([a-z]*)/([a-z]*)$   wp_content/plugins/career/mkr.php?page_id=$1&r_id=$2&user=$3&rtype=$4 [L]


This rule means that is we encounter a url which starts with builder followed by an integer again followed by an integer then an alphabet then an alphabet and then end convert it to the url after space for example

A Url

domain.com/builder/3/6/alpha/beta will be converted to

domain.com/wp_content/plugins/career/mkr.php?page_id=3&r_id=6&user=alpha&rtype=beta

That's how translation occurs

Unable to upload files from form

enctype=multipart/form-data

Always when adding input type="file" in your form add this parameter to your form tag as a property.....



now what does this mean

When submitting a form, you're trying to say your browser to send via the HTTP protocol a message on the network properly enveloped in a TCP/IP protocol message structure. When sending data, you can use POST or GET modes to send data using HTTP protocol. POST tells your browser to build an HTTP message and put all content in the header of the message ( a very useful way of doing things, more safe and also flexible). GET has some constraints about data representation and length.
When sending a file, it is necessary to tell HTTP protocol that you are sending a file having several characteristics and information inside it. In this way it is possible to consistently send data to receiver and let him open the file with the current format and so on... This is a requirement from the HTTP protocol as shown here:http://www.w3.org/TR/html401/interact/forms.html
You cannot send files using default send enctype parameters because your receiver might encounter problems reading it (consider that a file is a descriptor for some data for a specific operating system, if you see things this way, maybe you'll understand why it is so important to specify a different enctype for files).
This way of doing things also ensures that some security algorithms work on your messages. This information is also used by application-level routers in order to act as good firewalls for external data.

Session data lost in chrome and Internet Explorer

In your header file or which ever file that loads first add the following piece of code

if(session_id()=='')
session_start();

This is a very simple way to start of session.Mostly now a days frameworks have this set already in their bootstrap files but still if you are loosing session you can start off session with this.

wordpress media upload cheating ' uh issue

Its and issue with media_upload.php and comes with some plugins on updating Wordpress

The solution is simple

if using SMOF
 
add_action('init','optionframework_mlu_init');
'posttype'=>'options'

If not using SMOF

tb_show('','media_upload.php?post_id='+jquery('#post_ID').attr('name')+'....)

find this line and change  

'post_id=0'

that's it

I know it's changing the core but if plugin does not releases its update that's how we need to manage.

Difference in == & === with example

I had a scenario in WordPress where to update and insert a record I used

$wpdb->insert and
$wpdb->update

now they both on success return "no of rows" and "1" on failure they return "0" and "0"(of type boolean which is false)

I was using same variable To check for their result as such on their failure I had to use I had to use

if($res= = =false)
{
}.
elseif($res= =0)
{
}

Redirection facebook authentication "An Error occured please try lator"

Check that app host address is same as in redirect url parameter of your PHP SDK

$params = array(
  'scope' => 'read_stream, friends_likes',
  'redirect_uri' => 'https://www.myapp.com/post_login_page'
);

$loginUrl = $facebook->getLoginUrl($params);

Sunday, October 21, 2012

Use the javascript element for jquery functions

I was working on one of the functions and had pass an js element to it and wanted to perform jquery functions which require an id in format $("#id")

Here is how to use jquery operations on an element received in js format


//ele is an checkbox element
function enabletext(ele)
{
    if(ele.checked==true)
    {
        var myid=ele.id;
        jQuery(eval("'#" + myid + "'")).parent().siblings("#qtyid").show();
    }
}