<?php 

// Rewrite Rules
function kanews_theme_rewrite() {

  $array = [
    [
      'id' => kanews_get_option('crypto-page'),
      'param' => 'coin'
    ],
    [
      'id' => kanews_get_option('weather-page'),
      'param' => 'sehir'
    ],
    [
      'id' => kanews_get_option('exchange-page'),
      'param' => 'hisse'
    ],
    [
      'id' => kanews_get_option('doviz-page'),
      'param' => 'parite'
    ],
    [
      'id' => kanews_get_option('emtia-page'),
      'param' => 'emtia'
    ],
  ];

  foreach( $array as $page ) {
    if( !empty( $page['id'] ) && get_post_status($page['id']) == 'publish' ) {
      $page['name'] = basename(get_permalink($page['id']));
      add_rewrite_tag('%'.$page['param']  .'%','([^/]*)');
      add_rewrite_rule(
        '^'.$page['name'].'/([^/]+)$',
        'index.php?pagename='.$page['name'].'&'.$page['param'].'=$matches[1]',
        'top');
      add_rewrite_rule(
        '^'.$page['name'].'/([^/]+)/page/([^/]+)$',
        'index.php?pagename='.$page['name'].'&'.$page['param'].'=$matches[1]&paged=$matches[2]',
        'top');
    }
  }
}
add_action( 'init', 'kanews_theme_rewrite' );

// Page Link
function kanews_get_page_link($param, $value, $page) {

  $array = [
    'crypto' => kanews_get_option('crypto-page'),
    'weather' => kanews_get_option('weather-page'),
    'exchange' => kanews_get_option('exchange-page'),
    'doviz' => kanews_get_option('doviz-page'),
    'emtia' => kanews_get_option('emtia-page'),
    'puan' => '',
    'namaz' => '',
    'gazete' => '',
    'exchange2' => '',
    'traffic' => '',
    'live' => '',
    'eczane' => '',
  ];

  $dynamic_link = get_page_link($array[$page]);

  if( !empty($array[$page]) ) 
  return esc_url( untrailingslashit($dynamic_link).'/'.$value.'/' );
  else
  return esc_url(add_query_arg($param, $value, $dynamic_link));
}

// Set Param
function kanews_theme_rewrite_set_par() {
  $array = [
    [
      'id' => kanews_get_option('crypto-page'),
      'param' => 'coin'
    ],
    [
      'id' => kanews_get_option('weather-page'),
      'param' => 'sehir'
    ],
    [
      'id' => kanews_get_option('exchange-page'),
      'param' => 'hisse'
    ],
    [
      'id' => kanews_get_option('doviz-page'),
      'param' => 'parite'
    ],
    [
      'id' => kanews_get_option('emtia-page'),
      'param' => 'emtia'
    ],
  ];
  foreach( $array as $page ) {
    if( !empty( $page['id'] ) ) {
      if( false !== get_query_var( $page['param'], false ) ){
        $_GET[$page['param']] = get_query_var( $page['param'] );
      }
    }
  }
}
add_action( 'parse_query', 'kanews_theme_rewrite_set_par' );