Php printf a href

PHP Programming/html output

There are a few different way you can display HTML using PHP. Generally, you will use the echo command to output something. This will be seen by a web browser, and then it will format it.

 get_header(); ?>        if ( have_posts() ) while ( have_posts() ) : the_post(); ?>  if ( !empty( $post->post_parent ) ) : ?> 

printf( '. __( '← Return to %s', 'appthemes' ) . '', get_the_title( $post->post_parent ) ); ?>

endif; ?> the_ID(); ?>" post_class(); ?>> the_title(); ?> printf( __( ', 'appthemes' ), 'meta-prep meta-prep-author', sprintf( '%3$s', get_author_posts_url( get_the_author_meta( 'ID' ) ), sprintf( esc_attr__( 'View all ads by %s', 'appthemes' ), get_the_author() ), get_the_author() ) ); ?> printf( __( ', 'appthemes' ), 'meta-prep meta-prep-entry-date', sprintf( '%2$s', esc_attr( get_the_time() ), get_the_date() ) ); if ( wp_attachment_is_image() ) echo ' ; $metadata = wp_get_attachment_metadata(); printf( __( 'Full size is %s pixels', 'appthemes' ), sprintf( '%3$s × %4$s', wp_get_attachment_url(), esc_attr( __( 'Link to full-size image', 'appthemes' ) ), $metadata['width'], $metadata['height'] ) ); > ?> edit_post_link( __( 'Edit', 'appthemes' ), ', '' ); ?> if ( wp_attachment_is_image() ) : ?> $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); foreach ( $attachments as $k => $attachment ) if ( $attachment->ID == $post->ID ) break; > $k++; // If there is more than 1 image attachment in a gallery if ( count( $attachments ) > 1 ) if ( isset( $attachments[ $k ] ) ) // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID ); else // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID ); > else // or, if there's only 1 image attachment, get the URL of the image $next_attachment_url = wp_get_attachment_url(); > ?>

$attachment_width = apply_filters( 'appthemes_attachment_size', 800 ); $attachment_height = apply_filters( 'appthemes_attachment_height', 800 ); echo wp_get_attachment_image( $post->ID, array( $attachment_width, $attachment_height ) ); ?>

previous_image_link( false, __('← prev', 'appthemes') ); ?>    next_image_link( false, __('next →', 'appthemes') ); ?> else : ?> echo wp_get_attachment_url(); ?>" title=" echo esc_attr( get_the_title() ); ?>" rel="attachment"> echo basename( get_permalink() ); ?> endif; ?> endwhile; // end of the loop ?> div class="clr">div> div>post--> div> /shadowblock --> div> /shadowblock_out --> div class="clr">div> div> /content_res --> div> /content_botbg --> div> /content --> php get_footer(); ?>

Breaking PHP for Output [ edit | edit source ]

In addition to using functions such as echo and print, you can also end your script, and anything beyond the end of the script will be output as normal HTML to the browser. You can also restart your script whenever you want after you’ve closed the PHP tag. Confused? It’s actually pretty simple.

Let’s say you had a for loop to count up to five and output it.

While I would tend to use templates for larger pages that output a lot, we’ll get to that later. Remember how all your PHP scripts start with ? Those don’t have to be the very start and end of your file. In fact, PHP handles ending and restarting scripting just like if everything between the ?> and

Thus, you could do something like this:

This is actually a very common method of outputting variables in a script, especially if there is a lot of HTML surrounding the variables. As I said before, I personally rarely ever do this, as in my opinion, using echo for smaller scripts keeps your code cleaner (and I would use templates for larger ones). However, we want to cover most of the language here, so this is another method you could use.

Источник

Using printf & sprintf In WordPress – 12 Code Examples

If you want to add a link outside your editor, you’ll need to code it into a custom function or add it directly in a theme file. Otherwise, you could create a new widget area and add the HTML for the link into the widget. Not a very efficient way to add links in your theme, but works nonetheless.

To add your links in a custom function, you could create the link in your editor and output your text to the front end using echo:

A better and more efficient way is to use printf in your code like this:

Or, directly in a file like this:

printf without the %s placeholder.

add_action( 'loop_start', 'printf_demo' ); function printf_demo()

Using printf with wp_kses and a variable as your URL

$url = $audio_url; $link = sprintf( wp_kses( __( 'Download', '$text_domain' ), array( 'a' => array( 'href' => array() ) ) ), esc_url( $url ) ); echo $link;

Or, when hard coding a URL

$url = 'http://example.com'; $link = sprintf( wp_kses( __( 'Download', '$text_domain' ), array( 'a' => array( 'href' => array() ) ) ), esc_url( $url ) ); echo $link;

sprintf With Images

add_action( 'genesis_after_header', 'after_header_banner' ); function after_header_banner() < $output = sprintf( '%s', get_stylesheet_directory_uri() .'/images/bg1.jpg', get_the_title( $post->ID ) ); echo $output; >

printf with images

add_action( 'genesis_after_header', 'after_header_banner' ); function after_header_banner() < printf( '%s', get_stylesheet_directory_uri() .'/images/bg1.jpg', get_the_title( $post->ID ) ); >

Linking Image From Images Folder To Post Permalink

add_action( 'genesis_after_header', 'after_header_banner' ); function after_header_banner() < $output = sprintf( '', get_permalink(), get_stylesheet_directory_uri() .'/images/bg1.jpg', get_the_title( $post->ID ) ); echo $output; >

Linking Featured Images To Permalink

if ( $image = genesis_get_image( array( 'format' => 'url', 'size' => 'thumbnail' ) ) ) < printf( '', get_permalink(), $image, the_title_attribute( 'echo=0' ) ); >

Linking Image To Home URL

add_action( 'genesis_after_header', 'from_child_themes_images_folder' ); function from_child_themes_images_folder() < $image = sprintf( '%s/images/default.png', get_stylesheet_directory_uri() ); printf( ' ', esc_url( home_url( '/' ) ), $image ); >

Linking Image From Customizer To Home URL

add_action( 'genesis_header', 'image_from_customizer' ); function image_from_customizer() ', esc_url( home_url( '/' ) ), get_header_image() ); >

Use with ternary

printf( genesis_html5() ? '

%s

', do_shortcode( $post_info ) );

Resources

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

Code written by Brad Dalton specialist for Genesis, WooCommerce & WordPress theme customization. Read More…

Источник

PHP и MySQL

Сейчас поработаем с параметрами запроса. Как вы уже наверняка знаете, существует три способа передачи параметров запроса. Первый, использовать метод GET в форме. Второй – набрать параметры прямо в адресной строке броузера. И третий, это вставить параметры в обычную ссылку на странице. То есть сделать ссылку примерно такого вида

Научимся создавать такие ссылки на лету.

Для начала, давайте обратимся к базе данных и выведем список персонала. Взгляните на следующий код. Многое в нем вам будет знакомо.

  %s %s
\n", $PHP_SELF, $myrow["id"],$myrow["first"], $myrow["last"]); >while ($myrow = mysql_fetch_array($result)); >else < echo "Sorry, no records were found!"; >?>

Все вам должно быть знакомо, кроме функции printf() . Поэтому, давайте рассмотрим ее поближе. Во-первых, обратите внимание на обратные косые черты. Они говорят PHP-движку, что необходимо вывести символ, следующий за чертой, а не рассматривать его, как служебный символ или как часть кода. В данном случае это касается кавычки, которая нам нужна в тексте ссылки, но для PHP является символом окончания текстовой строки.

Далее, в коде используется интересная переменная $PHP_SELF . В этой переменной всегда хранится имя и URL текущей страницы. В данном случае эта переменная важна для нас потому, что мы хотим через ссылку вызвать страницу из нее самой. То есть вместо того, чтобы делать две страницы, содержащие разные коды для разных действий, мы все действия запихнули в одну страницу. С помощью условий if-else мы будем переводить стрелки с одного кода на другой, гоняя одну и ту же страницу по кругу. Это конечно увеличит размер страницы и время, необходимое на ее обработку, но в некоторых случая, такой трюк очень удобен.

Переменная $PHP_SELF гарантирует нам, что наша страница будет работать даже в том случае, если мы перенесем ее в другой каталог или даже на другую машину.

Ссылки, сгенерированные в цикле ссылаются на ту же самую страницу, только к имени самой страницы на лету добавлена некоторая информация: переменные и их значения.

Переменные, которые передаются в строке-ссылке, автоматически создаются PHP-движком, и к ним можно обращаться так, как если бы вы их создавали в коде сами. При втором проходе страницы наша программа отреагирует на эти пары name=value и направит ход исполнения на другие рельсы. В данном случае мы проверим, есть ли переменная $id , и в зависимости от результата выполним тот или иной код. Вот как это будет выглядеть:

  ", $myrow["first"]); printf("Last name: %s\n
", $myrow["last"]); printf("Address: %s\n
", $myrow["address"]); printf("Position: %s\n
", $myrow["position"]); >else < // show employee list $result = mysql_query("SELECT * FROM employees",$db); if ($myrow = mysql_fetch_array($result)) < // display list if there are records to display do< printf("%s %s
\n", $PHP_SELF, $myrow["id"], $myrow["first"], $myrow["last"]); >while ($myrow = mysql_fetch_array($result)); >else < // no records to display echo "Sorry, no records were found!"; >> ?>

Код усложнился, поэтому мы добавили в него некоторые комментарии, чтобы он стал яснее. Для однострочных комментариев можно использовать символы //. Если комментарий нужно уместить на нескольких строчках, используйте скобки /* . */.

Итак, вы наконец создали действительно полезную PHP-страницу, работающую с MySQL.

Источник

Php printf a href

Почему значение переменной не выводится на страницу? Как правильно прописать?
.

$per=»proverka»;
printf(«%s»,$per);
?>

.

в php нет функции printf.
есть echo и print
print ( string $arg )
echo ( string $arg1 [, string $argn. ] )

в php нет функции printf.
есть echo и print
print ( string $arg )
echo ( string $arg1 [, string $argn. ] )

$pagedata [«id»], $pagedata [«title»], $pagedata [«introtext»], $pagedata [«id»], $pagedata [«author»], $pagedata [«date»], $pagedata [«views»]);
>
while ( $pagedata = mysql_fetch_array( $dbdata ));
?>

И всё работает у человека, который его рекомендует, вот у меня только не работает

$pagedata [ «id» ], $pagedata [ «title» ], $pagedata [ «introtext» ], $pagedata [ «id» ], $pagedata [ «author» ], $pagedata [ «date» ], $pagedata [ «views» ]);
>
while( $pagedata = mysql_fetch_array ( $dbdata ));
?>

Наверно дело не в синтаксисе. Создаю новый php документ и вставляю несколько простейших примеров фоматного вывода, скопированных с разных сайтов по программированию. Редактор ошибок не выдаёт, но и выводить тоже ничего не выводит.
В чем может быть дело, если не в синтаксисе?

Наверно дело не в синтаксисе. Создаю новый php документ и вставляю несколько простейших примеров фоматного вывода, скопированных с разных сайтов по программированию. Редактор ошибок не выдаёт, но и выводить тоже ничего не выводит.
В чем может быть дело, если не в синтаксисе?

P.S. думаю не стоит говорить что язык php серверный

Чесно говоря, я совсем недавно занимаюсь сайтами, до этого я занимался С++.
Apache у меня установлен и запущен, если вы об этом.
Команда тоже не дает результатов

Чесно говоря, я совсем недавно занимаюсь сайтами, до этого я занимался С++.
Apache у меня установлен и запущен, если вы об этом.
Команда тоже не дает результатов

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Вопрос по php mail функции agent007 PHP 25 30.09.2010 12:45
спецификатор формата вывода функции printf Айат Помощь студентам 3 21.02.2010 13:12
printf zmey31313 Помощь студентам 4 13.01.2010 18:29
Отключение функции (PHP) LonsdaleAC Помощь студентам 1 13.11.2009 17:24

Источник

Читайте также:  Range to array kotlin
Оцените статью