Как я могу зарегистрировать в WordPress каждую запись из таблицы базы данных в качестве шорткода - PullRequest
0 голосов
/ 19 февраля 2019

Мне нужна помощь, и я надеюсь, что вы можете мне помочь.

Я начинающий разработчик WordPress, и я пытаюсь разработать плагин шорткодов, который позволит мне в любое время добавлять новые шорткоды в WP Admin и показывать их во внешнем интерфейсе.

Я не использую типы сообщений WP.Я создал отдельную таблицу только с 2 полями: shortcode_title и shortcode_value.Я могу добавлять, редактировать и удалять шорткоды.

Проблема в том, что я должен зарегистрировать каждый 'shortcode_title' в качестве шорткода.Я не могу запустить функцию, связанную с add_shortcode, в цикле, и я застрял.

Код, который добавляет шорткоды в базу данных:

if($_REQUEST['param']=="save_shortcode"){

    $form_data = array(
    'shortcode_title' => sanitize_text_field( $_REQUEST['frm_title'] ),
    'shortcode_value' => sanitize_text_field( $_REQUEST['frm_value'] )
     );

    // save data into db table
    $wpdb->insert("ds_shortcodes", $form_data);
}

Сейчас я добавил 1 шорткод, и яЯ написал функцию для добавления его в шорткод в WordPress.

function ds_shortcodes_page_functions_DSexe(){
global $wpdb;
$shortcode_id = "Software";
$shortcode_details = $wpdb->get_row("SELECT shortcode_value FROM ds_shortcodes WHERE shortcode_title like '$shortcode_id'", ARRAY_A);

return $shortcode_details['shortcode_value'];
}

add_shortcode("Software","ds_shortcodes_page_functions_DSexe"); 

Но мне приходится дублировать эту функцию вручную в PHP для каждого шорткода, который я добавляю в admin.

Я пробовал это:

function shortcode_content(){

global $wpdb;
$all_shortcodes = $wpdb->get_results("SELECT shortcode_title, shortcode_value FROM ds_shortcodes");

    foreach($all_shortcodes as $each_shortcode){
        return $each_shortcode['shortcode_value'];
    }

}

function shortcode_add(){

    foreach($all_shortcodes as $each_shortcode){
       add_shortcode($each_shortcode->shortcode_title,'shortcode_content');
    }

}

Мне нужно вытащить все записи из базы данных в цикле, и для каждого 'shortcode_value' я должен добавить соответствующий 'shortcode_title' в качестве шорткода.

Если я напечатаю $ all_shortcodes, я получаю массив, подобный следующему:

Array
(
[0] => stdClass Object
    (
        [shortcode_title] => Software
        [shortcode_value] => test.exe
    )

[1] => stdClass Object
    (
        [shortcode_title] => Version
        [shortcode_value] => 10
    )

[2] => stdClass Object
    (
        [shortcode_title] => Size
        [shortcode_value] => 412 MB
    )

[3] => stdClass Object
    (
        [shortcode_title] => DS1
        [shortcode_value] => 11111111111111
    )

[4] => stdClass Object
    (
        [shortcode_title] => DS2
        [shortcode_value] => 22222222222222
    )

[5] => stdClass Object
    (
        [shortcode_title] => DS3
        [shortcode_value] => 33333333333333
    )

)

Я также попробовал вот что: Кажется, это имеет больше смысла, но что-то все еще отсутствует.

function shortcode_content($short_title, $short_value){
  global $wpdb;
  $all_shortcodes = $wpdb->get_results("SELECT shortcode_title, shortcode_value FROM ds_shortcodes", ARRAY_A);
  foreach($all_shortcodes as $each_shortcode){
    $short_title =  $each_shortcode['shortcode_title'];
    $short_value =  $each_shortcode['shortcode_value'];
    return $short_title;
    return $short_value;
  }

}


function shortcode_add(){

  foreach($short_value as $key){
    add_shortcode($short_title,array('shortcode_content'));
  }

}

Вторая функция, похоже, не получает переменные из первой.

Я также поместил переменные из первой функции в массив, но все еще не работает.

function shortcode_content($short){
  global $wpdb;
  $all_shortcodes = $wpdb->get_results("SELECT shortcode_title, shortcode_value FROM ds_shortcodes", ARRAY_A);
  foreach($all_shortcodes as $each_shortcode){
    $short_title =  $each_shortcode['shortcode_title'];
    $short_value =  $each_shortcode['shortcode_value'];
    $short =  array ($short_title, $short_value);
    return $short;
  }

}

function shortcode_add(){

  foreach($short_value as $key){
    add_shortcode($short_title,array('shortcode_content'));
  }

}

Я думаю, что все ближе, но все равно не работает.:)

Я знаю, что это должно быть легко, но как новичок, это кажется довольно сложным.

После 2 дней попыток я был бы очень признателен за вашу помощь.

Спасибо.

Алин

Ответы [ 2 ]

0 голосов
/ 19 февраля 2019

Вам нужно будет также получить данные шорткода в функции shortcode_add

Вот полное рабочее решение ..

if(! function_exists('shortcode_content')){

    function shortcode_content( $atts, $content = null,$tag)    {
        global $wpdb;

        extract( shortcode_atts( array(
                    'shortcode_extra_data' => '', // available as $shortcode_extra_data
                ), $atts 
            ) 
        );

        $shortcode_value = $wpdb->get_var("SELECT shortcode_value FROM ds_shortcodes where shortcode_title = '".$tag."'");

        // do something with cotent
        // add shortcode_value with content provided in shortcode
        $content = $content.$shortcode_value;

        $content = apply_filters('the_content', $content); // use this according to your requirment, remove if not needed
        // return processed content
        return $content;

    }
}

/*
* call function on init hook
*/
add_action( 'init', 'shortcode_add' );
if(! function_exists('shortcode_add')){

    function shortcode_add(){
        global $wpdb;

        $all_shortcodes = $wpdb->get_results("SELECT shortcode_title, shortcode_value FROM ds_shortcodes", ARRAY_A);
        foreach($all_shortcodes as $short){
            add_shortcode($short['shortcode_title'],'shortcode_content');
        }

    }
}

И шорткод для вызова

[short1 shortcode_extra_data="syzzzzzz"]something inside content[/short1]
0 голосов
/ 19 февраля 2019

Заметили ли вы, что когда вы делаете print_r, чтобы получить объект stdClass, но когда вы пытаетесь использовать shortcode_title из этого объекта, вы ошибочно вызываете его, поскольку это не объект, а массив.

Неверно:

   add_shortcode($each_shortcode['shortcode_title'],'shortcode_content');

Правильно:

   add_shortcode($each_shortcode->shortcode_title,'shortcode_content');
...