Improved the output of the related posts in WordPress 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-&gt;cat_ID == 10 || $cat1-&gt;cat_ID == 10 || $cat2-&gt;cat_ID == 10 || $cat3-&gt;cat_ID == 10 || $cat4-&gt;cat_ID == 10 || $cat5-&gt;cat_ID == 10 || $cat6-&gt;cat_ID == 10){
        $post = get_the_ID();
        $args = array('cat'=&gt;10, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post));
    } elseif ($cat0-&gt;cat_ID == 12 || $cat1-&gt;cat_ID == 12 || $cat2-&gt;cat_ID == 12 || $cat3-&gt;cat_ID == 12 || $cat4-&gt;cat_ID == 12 || $cat5-&gt;cat_ID == 12 || $cat6-&gt;cat_ID == 12){
        $post = get_the_ID();
        $args = array('cat'=&gt;12, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post));               
    } else {
        $cat = $cat[0];
        $cat = $cat-&gt;cat_ID;
        $post = get_the_ID();
        $args = array('cat'=&gt;$cat, 'orderby' =&gt; 'date', 'showposts' =&gt; $related,'post__not_in' =&gt; array($post));
    }

$related = new WP_Query($args); 


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

Thanks
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]-&gt;cat_ID;
}
$post = get_the_ID();
$args = array('cat'=&gt;$cat, 'orderby' =&gt; 'date',
    'showposts' =&gt; $related,'post__not_in' =&gt; array($post));