1
\$\begingroup\$

I made a simple code to improve the results for WordPress related posts area and it works fine , but because my experience in coding is low , my code is very long and i believe that there is a way to make simple and better

here is the code :-

$cat = get_the_category();
$cat0 = $cat[0];
$cat1 = $cat[1];
$cat2 = $cat[2];
$cat3 = $cat[3];
$cat4 = $cat[4];
$cat5 = $cat[5];
$cat6 = $cat[5];

    if ($cat0->cat_ID == 10 || $cat1->cat_ID == 10 || $cat2->cat_ID == 10 || $cat3->cat_ID == 10 || $cat4->cat_ID == 10 || $cat5->cat_ID == 10 || $cat6->cat_ID == 10){
        $post = get_the_ID();
        $args = array('cat'=>10, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));
    } elseif ($cat0->cat_ID == 12 || $cat1->cat_ID == 12 || $cat2->cat_ID == 12 || $cat3->cat_ID == 12 || $cat4->cat_ID == 12 || $cat5->cat_ID == 12 || $cat6->cat_ID == 12){
        $post = get_the_ID();
        $args = array('cat'=>12, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));               
    } else {
        $cat = $cat[0];
        $cat = $cat->cat_ID;
        $post = get_the_ID();
        $args = array('cat'=>$cat, 'orderby' => 'date', 'showposts' => $related,'post__not_in' => array($post));
    }

$related = new WP_Query($args); 

Also, i tried to use "foreach" function but it always fails in "else" part

Thanks

\$\endgroup\$
1
\$\begingroup\$

The major thing for me in this code is the repetition forms a large part of it. You can also use some of the features of PHP to stop having to move data around and comparing individual items.

Using array_column() (this requires PHP 7+ as your input is an array of objects) to fetch all of the values of cat_ID, stops you having to extract the values from the objects and then compare each one individually. You can then use in_array() to check for each value against all of them in one call rather than the list of || conditions.

Then the code setting $args is the same in each branch of your if, so I've reduced this to each branch sets $cat (as your last branch already does) and then this is used by the same code outside the if...

$cat = get_the_category();

$categories = array_column($cat, "cat_ID");
if ( in_array(10, $categories) ){
    $cat = 10;
} elseif (in_array(12, $categories)){
    $cat = 12;
} else {
    $cat = $cat[0]->cat_ID;
}
$post = get_the_ID();
$args = array('cat'=>$cat, 'orderby' => 'date',
    'showposts' => $related,'post__not_in' => array($post));
\$\endgroup\$
  • \$\begingroup\$ Can't thank you enough for your awesome code and explanation, works like a charm. \$\endgroup\$ – sammax Nov 4 at 17:55

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.