Отображение содержимого редактора сообщений WordPress в выходных данныхPhp

Кемеровские программисты php общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Отображение содержимого редактора сообщений WordPress в выходных данных

Сообщение Anonymous »

Я написал динамическую панель для своей темы WordPress, которую вызываю с помощью короткого кода в редакторе WordPress и помещаю в нее свой контент.
Мой контент отлично отображается на выходе , но с точки зрения порядка все перепутано!?
Я попробовал много методов и, в конце концов, мне удалось в некоторой степени управлять выводом сообщений с помощью следующего кода:< /p>
// The function of displaying the format of the content in the output
function wrap_in_p_if_needed($content) {

$content = preg_replace('/]*src="([^"]+)"\s+[^>]*>/is', '', $content); // Remove img tags

$content = preg_replace('/\[video\s+width="(\d+)" height="(\d+)"\s+mp4="([^"]+)"]\[\/video\]/is', '', $content); // Remove video tags

$content = preg_replace('/\[audio\s+mp3="([^"]+)"]\[\/audio\]/is', '', $content); // Remove audio tags

// divide the content into paragraphs based on **
$paragraphs = explode('**', $content);

// Create a new string to store the output
$output = '';

// Append each paragraph to the output string in a
tag
foreach ($paragraphs as $paragraph) {
$output .= '' . trim($paragraph) . '
';
}

return $output;
}

В приведенном выше коде мне удалось разделить слипшиеся абзацы с помощью знака **, но есть еще одна проблема, для которой у меня нет решения!< /p>
Если оно находится в содержании медиа (фото-видео-аудио) между абзацами, оно переместится в конец панели?
Другими словами, сначала отображаются абзацы, а затем медиа!?
Теперь я просто хочу изменить приведенную выше функцию, чтобы мне не приходилось использовать знаки ** больше разделять абзацы и выводимый контент отображается корректно и без проблем.
Весь код, который я написал для динамической панели, выглядит следующим образом:
function dynamic_panel($title, $content) {

// Add var_dump to see content before wp_kses (optional) (for testing)
// var_dump($content);

// Sanitize title to prevent XSS
$sanitized_title = wp_kses($title, ['

']);

// Sanitize content to prevent XSS
$sanitized_content = wp_kses($content, array(
'p' => array(),
'span' => array(),
'strong' => array(),
'i' => array(),
'br' => array(),
'em' => array(),
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
'video' => array(),
'audio' => array(),
'img' => array(),
));

echo '';
echo '';
echo '
  • ';
    echo '
  • ';
    echo '­
    ';
    echo '
    ­
    ';
    echo '' . $sanitized_title . '';
    echo '';
    echo '';
    echo '';

    // Use the wrap_in_p_if_needed function to format the content
    $formatted_content = wrap_in_p_if_needed($sanitized_content);

    // Display content with formatting
    echo $formatted_content;

    // Process and display images (including GIFs)
    if (preg_match_all('/]*src="([^"]+)"\s+[^>]*>/is', $content, $matches)) {
    foreach ($matches[1] as $image_url) {
    echo '';
    }
    }

    // Process and display videos using wp_video_shortcode or oEmbed
    if (preg_match('/\[video\s+width="(\d+)" height="(\d+)"\s+mp4="([^"]+)"]\[\/video\]/is', $content, $matches)) {
    $video_url = esc_url( $matches[3] );

    // First we try to display the local video
    $video_embed = wp_video_shortcode( '[video mp4="' . $video_url . '" width="' . $matches[1] . '" height="' . $matches[2] . '"]' );

    // If the local video is not displayed, we use oEmbed
    if ( empty( $video_embed ) ) {
    $video_embed = wp_oembed_get( $video_url, array( 'width' => $matches[1], 'height' => $matches[2] ) );
    }

    if ($video_embed) {
    echo $video_embed;
    } else {
    echo '
    Error embedding video
    ';
    }
    }

    // Process and display audio using wp_audio_shortcode
    if (preg_match('/\[audio\s+mp3="([^"]+)"]\[\/audio\]/is', $content, $matches)) {
    $audio_url = $matches[1];
    $audio_embed = wp_audio_shortcode('[audio mp3="' . $audio_url . '"]');
    echo $audio_embed;
    }

    echo '';
    echo '';
    echo '
';
echo '';
echo '';
echo '';
echo '';
}

// The function of displaying the format of the content in the output
function wrap_in_p_if_needed($content) {

$content = preg_replace('/]*src="([^"]+)"\s+[^>]*>/is', '', $content); // Remove img tags

$content = preg_replace('/\[video\s+width="(\d+)" height="(\d+)"\s+mp4="([^"]+)"]\[\/video\]/is', '', $content); // Remove video tags

$content = preg_replace('/\[audio\s+mp3="([^"]+)"]\[\/audio\]/is', '', $content); // Remove audio tags

// divide the content into paragraphs based on **
$paragraphs = explode('**', $content);

// Create a new string to store the output
$output = '';

// Append each paragraph to the output string in a
tag
foreach ($paragraphs as $paragraph) {
$output .= '' . trim($paragraph) . '
';
}

return $output;
}

function dynamic_panel_shortcode($atts, $content) {
$title = $atts['title'] ?? '';
if (!$content) {
$content = $atts['content'] ?? '';
}

return dynamic_panel($title, $content);
}

add_shortcode('panel', 'dynamic_panel_shortcode');


Подробнее здесь: https://stackoverflow.com/questions/790 ... the-output
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Php»