I'm working on a shortcode to display a custom post type, which mostly works. I don't control the feed this data is coming from, hence the need to split up the title based on delimiters. The problem I'm experiencing is that the variables first, second, third, and fourth can be null, and I don't know how to account for this in this context.
Any tips appreciated.
add_shortcode( 'parliament-posts', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'parl',
'post_status' => 'publish',
'pagination' => true,
'posts_per_page' => '10',
'orderby' => 'date',
'paged' => $paged
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$string .= '<div >';
$string .= '<img src="/wp-content/uploads/thumbnail.jpg" alt="Photo of Joe Blogs">';
$string .= '<div >';
$title = (get_the_title ());
$str = preg_split('(\||\[|\]|=)', $title,-1, PREG_SPLIT_NO_EMPTY);
print_r($title);
$first = $str[0];
$second = $str[1];
$third = $str[2];
$fourth = $str[3];
$string .= '<h3 ><div>' . $first . '</div></h3>';
$string .= '<h5>' . $second . ' ' . $third . ' ' . $fourth . '</h5>';
$string .= '</div>';
$string .= '<div >' . get_the_date() . '</div>';
$string .= '<div ><a href="' . get_permalink() . 'target="_blank" rel="noopener">View in context</a></div>';
$string .= '</div>';
$string .= '<article >' . get_the_content() . '</article>';
}
$string .= '</div>';
}
$string .= '<div >';
$string .= '<div >' . previous_posts_link( 'Newer Posts' ) . '</div>';
$string .= '<div >' . next_posts_link( 'Older Posts', $query->max_num_pages ) . '</div>';
$string .= '</div>';
return $string;
}
CodePudding user response:
you can check if value that come from html is empty string and make for loop to transfer empty string to null
foreach($_POST as $key => $value){
if($value === ""){
$_POST[$key] = null;
}
}
you can you also isset($var);
also to check if variable have null value or undefine variable.
CodePudding user response:
UPDATE:
In a comment you said that $str[0] is always populated and the others vars can be null:
$string .= '<h3 ><div>' . $str[0] . '</div></h3>';
unset($str[0]);
if (!empty($str) {
$string .= '<h5>' . implode(' ', $str) . '</h5>';
}
I used $str[0] in h3. I deleted it and imploded whatever remained if it wasn't empty. This is shorter than using $first, $second, $third, $fourth, etc.