1

I have the following which works fine but only cache first value for first post and doesn't store data for all movie posts in database. How I can solve this problem? I have also a live perview of this theme.

$cinemamoviename    = get_post_meta( $post->ID, "cinama_moviename", true );
$cinemamovieyear    = get_post_meta( $post->ID, "cinama_movieyear", true );
$cinemamovienames   = urlencode( $cinemamoviename );

$json   = file_get_contents( 'http://www.omdbapi.com/?t=' . $cinemamovienames . '&y=' . $cinemamovieyear . '&plot=short&r=json' );
$obj    = json_decode( $json );

$movies_title   = $obj->Title;
$movies_year    = $obj->Year;
$movies_datas   = array( $movies_title, $movies_year );     

set_transient( 'get_movies_data_intrans', $movies_datas, 365 * DAY_IN_SECONDS );

$movies_details = get_transient( 'get_movies_data_intrans' ); 

if( false === $movies_details ){ set_transient( 'get_movies_data_intrans', $movies_datas, 365 * DAY_IN_SECONDS ); }

  ?>

<ul>
    <li>
        <b>Title</b> :
      <?php
        if ( $movies_details[0] == null ) {
            echo "N/A";
        } else { 
            echo $movies_details[0];
        }
      ?>
    </li>
    <li>
        <b> Relase Date </b> : 
      <?php
        if ( $movies_details[1] == null ) {
            echo "N/A";
        }else{
            echo $movies_details[1];
        }
      ?>
    </li>
</ul>
  • any anwser please? – Poorya Jan 19 '17 at 0:44
1

The reason it's only storing the first post data is because you're using the same transient name for each post. If you want to store multiple movie transients, you need unique names for each movie.

Also, the way you're getting the transient defeats the purpose of using transients. You want to first try to get the transient and if it's not available, then generate a value and set that as the transient.

Here's how I would modify your code:

<?php
  $cinemamoviename    = get_post_meta( $post->ID, "cinama_moviename", true );
  $cinemamovieyear    = get_post_meta( $post->ID, "cinama_movieyear", true );
  $cinemamovienames   = urlencode( $cinemamoviename );

  $transient_name = "get_movies_data_intrans_$cimemamoviename_$cinemamovieyear";
  if( false === ( $movies_details = get_transient( $transient_name ) ) ) {
    $args = array(
      't'    => $cinemamovienames,
      'y'    => $cinemamovieyear,
      'plot' => 'short',
      'r'    => 'json',
    );
    $url    = add_query_arg( $args, 'http://www.omdbapi.com/' );
    $json   = wp_remote_get( $url );
    $obj    = json_decode( $json );

    $movies_title   = $obj->Title;
    $movies_year    = $obj->Year;
    $movies_datas   = array( $movies_title, $movies_year );     

    set_transient( $transient_name, $movies_datas, 365 * DAY_IN_SECONDS );    
  }
?>
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.