qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
270,281 | <p>I have a very basic theme that is running WooCommerce beautifully so far. In my functions.php I've setup the following to support <code>woocommerce</code>.</p>
<pre><code>//
// WooCommerce Hooks and Theme Overrides
//
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
add_action('woocommerce_before_main_content', 'cm_theme_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'cm_theme_wrapper_end', 10);
function cm_theme_wrapper_start() {
echo '
<div class="main-content-wrapper">
<section class="layout-standard">
<section class="cards">
<div class="layout-gallery short">
<div class="background"></div>
<img class="background-image" src="'; if ( has_post_thumbnail() ) { the_post_thumbnail_url('header-bg'); } else { echo get_template_directory_uri().'/images/default.jpg'; } echo '" alt="'; $image_title = get_post(get_post_thumbnail_id())->post_title; echo $image_title; echo '" title="'; $image_title = get_post(get_post_thumbnail_id())->post_title; echo $image_title; echo '">
<div class="width-container">
<div class="inner-container">
<h1 class="section-title">'; woocommerce_page_title(); echo '</h1>
</div>
</div>
</div>
</section>
<div class="width-container">
<div class="content-container">
<div class="content-holder">';
}
function cm_theme_wrapper_end() {
echo '
</div>
</div>
</div>
<div class="sidebar-container">';
get_sidebar();
echo '
</div>
</section>
</div>';
}
</code></pre>
<p>This works great, however on the shop base page it is not showing the pages featured image. However it is showing the last product image. This is basically an archive page, but outside of WordPress I guess. </p>
<p><strong>How can I get the featured image of the base shop page to show instead of the last product image?</strong></p>
| [
{
"answer_id": 270269,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect a theme error. Try a different theme (like the standard ones - Twenty-whatevers).</p>\n"
},
{
"answer_id": 276354,
"author": "Emilien Schneider",
"author_id": 121184,
"author_profile": "https://wordpress.stackexchange.com/users/121184",
"pm_score": 2,
"selected": true,
"text": "<p>I found it at last!</p>\n\n<p>Using the browser debugger, I found that there was a \"editor.wp\" which was undefined (in the complete version of the js file).\nThen I understood that the \"wordpress\" plugin was not used in the editor.</p>\n\n<p>When calling the function wp_editor, I was setting a list of plugin : paste, wplink, textcolor.\nIt was working until a specific WordPress update.</p>\n\n<p>I just had to add the \"wordpress\" plugin in the list, and now it's working.</p>\n"
}
]
| 2017/06/15 | [
"https://wordpress.stackexchange.com/questions/270281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44017/"
]
| I have a very basic theme that is running WooCommerce beautifully so far. In my functions.php I've setup the following to support `woocommerce`.
```
//
// WooCommerce Hooks and Theme Overrides
//
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
add_action('woocommerce_before_main_content', 'cm_theme_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'cm_theme_wrapper_end', 10);
function cm_theme_wrapper_start() {
echo '
<div class="main-content-wrapper">
<section class="layout-standard">
<section class="cards">
<div class="layout-gallery short">
<div class="background"></div>
<img class="background-image" src="'; if ( has_post_thumbnail() ) { the_post_thumbnail_url('header-bg'); } else { echo get_template_directory_uri().'/images/default.jpg'; } echo '" alt="'; $image_title = get_post(get_post_thumbnail_id())->post_title; echo $image_title; echo '" title="'; $image_title = get_post(get_post_thumbnail_id())->post_title; echo $image_title; echo '">
<div class="width-container">
<div class="inner-container">
<h1 class="section-title">'; woocommerce_page_title(); echo '</h1>
</div>
</div>
</div>
</section>
<div class="width-container">
<div class="content-container">
<div class="content-holder">';
}
function cm_theme_wrapper_end() {
echo '
</div>
</div>
</div>
<div class="sidebar-container">';
get_sidebar();
echo '
</div>
</section>
</div>';
}
```
This works great, however on the shop base page it is not showing the pages featured image. However it is showing the last product image. This is basically an archive page, but outside of WordPress I guess.
**How can I get the featured image of the base shop page to show instead of the last product image?** | I found it at last!
Using the browser debugger, I found that there was a "editor.wp" which was undefined (in the complete version of the js file).
Then I understood that the "wordpress" plugin was not used in the editor.
When calling the function wp\_editor, I was setting a list of plugin : paste, wplink, textcolor.
It was working until a specific WordPress update.
I just had to add the "wordpress" plugin in the list, and now it's working. |
270,286 | <p>What's the difference beetween </p>
<p><code>define( 'WP_MEMORY_LIMIT', '96M' );</code>
and
<code>define( 'WP_MAX_MEMORY_LIMIT', '256M' );</code></p>
<p>In my host I have this </p>
<pre><code>define( 'WP_MEMORY_LIMIT', '786M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );
</code></pre>
<p>is this correct, should the <code>WP_MAX_MEMORY_LIMIT</code> be higher ?</p>
| [
{
"answer_id": 270288,
"author": "joetek",
"author_id": 62298,
"author_profile": "https://wordpress.stackexchange.com/users/62298",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>WP_MEMORY_LIMIT</code> is the default limit set in the front-end, but it can be raised up to <code>WP_MAX_MEMORY_LIMIT</code> in wp-admin pages, as well as certain other functions such as image manipulation.</p>\n\n<p>In short, you'll want to have the <code>WP_MEMORY_LIMIT</code> set primarily for front-end access, in a way that you won't use up your memory when many concurrent users hit the server. You'd want <code>WP_MAX_MEMORY_LIMIT</code> set higher to allow for admin functions that have heavier requirements, but lower concurrency.</p>\n"
},
{
"answer_id": 270289,
"author": "DaveLak",
"author_id": 119673,
"author_profile": "https://wordpress.stackexchange.com/users/119673",
"pm_score": 4,
"selected": false,
"text": "<p>WordPress tells us: </p>\n\n<blockquote>\n <p>the WP_MEMORY_LIMIT option allows you to specify the maximum amount of\n memory that can be consumed by PHP. This setting may be necessary in\n the event you receive a message such as \"Allowed memory size of xxxxxx\n bytes exhausted\".</p>\n</blockquote>\n\n<p>Or as the <a href=\"http://php.net/manual/en/ini.core.php#ini.memory-limit\" rel=\"noreferrer\">PHP docs put it</a> </p>\n\n<blockquote>\n <p>[A memory limit] helps prevent poorly written scripts for eating up all available\n memory on a server.</p>\n</blockquote>\n\n<p>The <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP\" rel=\"noreferrer\">WordPress Codex</a> also says this about these constants:</p>\n\n<blockquote>\n <p>This setting [<code>WP_MEMORY_LIMIT</code>] increases PHP Memory only for WordPress, not other\n applications. By default, WordPress will attempt to increase memory\n allocated to PHP to 40MB (code is at the beginning of\n /wp-includes/default-constants.php) for single site and 64MB for\n multisite, so the setting in wp-config.php should reflect something\n higher than 40MB or 64MB depending on your setup.</p>\n</blockquote>\n\n<p>And this about the <code>WP_MAX_MEMORY_LIMIT</code> specifically:</p>\n\n<blockquote>\n <p>Administration tasks require much [more] memory than [a] usual operation. When in\n the administration area, the memory can be increased or decreased from\n the WP_MEMORY_LIMIT by defining WP_MAX_MEMORY_LIMIT.</p>\n</blockquote>\n\n<p>So <code>WP_MEMORY_LIMIT</code> is the limit and <code>WP_MAX_MEMORY_LIMIT</code>, if set, will override the former in the admin.</p>\n\n<p>Now when you ask \"is this correct\", there is no way for us to tell you definitively.</p>\n\n<p>You may want to raise those limits if your site is growing in visitors and or active plugins but if you are not experiencing any issues I would say you are fine for now.</p>\n\n<p>If you choose to up the limits I have outlined the different methods to increase PHP memory in <a href=\"https://wordpress.stackexchange.com/a/268505/119673\">this answer</a>. Note the last part about your host potentially limiting this value.</p>\n"
}
]
| 2017/06/15 | [
"https://wordpress.stackexchange.com/questions/270286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119118/"
]
| What's the difference beetween
`define( 'WP_MEMORY_LIMIT', '96M' );`
and
`define( 'WP_MAX_MEMORY_LIMIT', '256M' );`
In my host I have this
```
define( 'WP_MEMORY_LIMIT', '786M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );
```
is this correct, should the `WP_MAX_MEMORY_LIMIT` be higher ? | WordPress tells us:
>
> the WP\_MEMORY\_LIMIT option allows you to specify the maximum amount of
> memory that can be consumed by PHP. This setting may be necessary in
> the event you receive a message such as "Allowed memory size of xxxxxx
> bytes exhausted".
>
>
>
Or as the [PHP docs put it](http://php.net/manual/en/ini.core.php#ini.memory-limit)
>
> [A memory limit] helps prevent poorly written scripts for eating up all available
> memory on a server.
>
>
>
The [WordPress Codex](https://codex.wordpress.org/Editing_wp-config.php#Increasing_memory_allocated_to_PHP) also says this about these constants:
>
> This setting [`WP_MEMORY_LIMIT`] increases PHP Memory only for WordPress, not other
> applications. By default, WordPress will attempt to increase memory
> allocated to PHP to 40MB (code is at the beginning of
> /wp-includes/default-constants.php) for single site and 64MB for
> multisite, so the setting in wp-config.php should reflect something
> higher than 40MB or 64MB depending on your setup.
>
>
>
And this about the `WP_MAX_MEMORY_LIMIT` specifically:
>
> Administration tasks require much [more] memory than [a] usual operation. When in
> the administration area, the memory can be increased or decreased from
> the WP\_MEMORY\_LIMIT by defining WP\_MAX\_MEMORY\_LIMIT.
>
>
>
So `WP_MEMORY_LIMIT` is the limit and `WP_MAX_MEMORY_LIMIT`, if set, will override the former in the admin.
Now when you ask "is this correct", there is no way for us to tell you definitively.
You may want to raise those limits if your site is growing in visitors and or active plugins but if you are not experiencing any issues I would say you are fine for now.
If you choose to up the limits I have outlined the different methods to increase PHP memory in [this answer](https://wordpress.stackexchange.com/a/268505/119673). Note the last part about your host potentially limiting this value. |
270,291 | <p>I am running into a strange issue where <code>content_arr['extended']</code> or <code>content_arr['main']</code> is removing the paragraph tags in the output.</p>
<p>Any help, or insight into something i am over looking, trying to resolve this would be greatly appreciated.</p>
| [
{
"answer_id": 270361,
"author": "Zach Smith",
"author_id": 1354,
"author_profile": "https://wordpress.stackexchange.com/users/1354",
"pm_score": 1,
"selected": false,
"text": "<p>seems when i add the following using <code>wpautop</code> to the output it resolves the problem. i would love to know from someone smarter than myself why this fixes it. why when we just use <code>the_content</code> the p tags are included, but when we use <code>get_extended</code> do the p tags get removed?</p>\n\n<pre><code>$content_arr = get_extended ( $post->post_content );\n\n if( strpos( get_the_content(), '<span id=\"more-' ) == true ) {\n echo wpautop($content_arr['main']);\n echo '<div class=\"morecontent\">'. wpautop($content_arr['extended']).'</div>';\n }\n else {\n the_content();\n }\n</code></pre>\n"
},
{
"answer_id": 302557,
"author": "Shaun Cockerill",
"author_id": 124137,
"author_profile": "https://wordpress.stackexchange.com/users/124137",
"pm_score": 0,
"selected": false,
"text": "<p><code>$post->post_content</code> does not have paragraph tags by default. Typically they are added when displayed using <code>the_content()</code> because <code>wpautop</code> is one of the filters applied when using this function. This also holds true for <code>do_shortcode</code> and a few other functions.</p>\n\n<p>When displaying extended content on the page, you should to pass each part through the functions <code>wpautop</code> and <code>do_shortcode</code> etc, or apply the filter <code>the_content</code> instead.</p>\n\n<pre><code><?php $parts = get_extended( $post->post_content ); ?>\n<div class=\"post_content\">\n <?php echo wpautop( do_shortcode( $parts['main'] ) ); // Not entirely sure of the best order. ?>\n <?php if ( ! empty( $parts['extended'] ) ) : ?>\n <!-- Example Bootstrap toggle link. -->\n <a href=\"#read-more\" data-toggle=\"collapse\" data-target=\"#read-more\">\n <?php _e( 'Read More' ); ?>\n </a>\n <div id=\"read-more\">\n <?php echo apply_filters( 'the_content', $parts['extended'] ); ?>\n </div>\n <?php endif; ?>\n</div>\n</code></pre>\n"
}
]
| 2017/06/15 | [
"https://wordpress.stackexchange.com/questions/270291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1354/"
]
| I am running into a strange issue where `content_arr['extended']` or `content_arr['main']` is removing the paragraph tags in the output.
Any help, or insight into something i am over looking, trying to resolve this would be greatly appreciated. | seems when i add the following using `wpautop` to the output it resolves the problem. i would love to know from someone smarter than myself why this fixes it. why when we just use `the_content` the p tags are included, but when we use `get_extended` do the p tags get removed?
```
$content_arr = get_extended ( $post->post_content );
if( strpos( get_the_content(), '<span id="more-' ) == true ) {
echo wpautop($content_arr['main']);
echo '<div class="morecontent">'. wpautop($content_arr['extended']).'</div>';
}
else {
the_content();
}
``` |
270,294 | <p>i am building the following script to query data from every child page of a certain page. i have it working fine, but i am unable to get the featured image, because i am using <code>$post->ID</code>. what would i change <code>$post->ID</code> to be in order to work correctly with the rest of my function? any help would be greatly appreciated.</p>
<pre><code>$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => 91,
'order' => 'ASC',
);
$parent = new WP_Query( $args );
if ( $parent->have_posts() ) :
echo '<div class="events_lists_on_page">';
while ( $parent->have_posts() ) : $parent->the_post();
//grab the menu item data
$image_uploaded_meta_id = get_post_meta($post->ID, '_listing_image_id', true);
$image_thumb_url = wp_get_attachment_image_src($image_uploaded_meta_id, 'full');
//grab and save title of post
$title = get_the_title();
//grab and save the link to the post
$link = get_permalink();
//grab content
$the_content = get_the_content();
echo '<div class="element">';
echo '<img src="'. $image_thumb_url[0] .'">';
echo '<div class="text"><p>' . $title .'</p></div>';
echo '<p>'. $the_content .'</p>';
echo '</div>';
endwhile;
echo '</div>';
endif;
</code></pre>
| [
{
"answer_id": 270296,
"author": "Asaf Lopez",
"author_id": 121826,
"author_profile": "https://wordpress.stackexchange.com/users/121826",
"pm_score": 3,
"selected": true,
"text": "<p>Try with <code>get_the_ID()</code></p>\n\n<pre><code>$image_uploaded_meta_id = get_post_meta(get_the_ID(), '_listing_image_id', true);\n</code></pre>\n\n<p><code>get_the_ID()</code> is a core Wordpress function that acts directly inside the Wordpress Loop, retrieving the id of the current item being loaded. <code>$post->id</code> is not working because the variable <code>$post</code> has no scope inside the loop.</p>\n\n<p>Here's the link to the documentation: <a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_the_id/</a></p>\n"
},
{
"answer_id": 270320,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": 0,
"selected": false,
"text": "<p>Define <strong>global $post</strong> when <strong>while loop start*</strong> like that below</p>\n\n<pre><code> while ( $parent->have_posts() ) : $parent->the_post();global $post;\n</code></pre>\n"
}
]
| 2017/06/15 | [
"https://wordpress.stackexchange.com/questions/270294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1354/"
]
| i am building the following script to query data from every child page of a certain page. i have it working fine, but i am unable to get the featured image, because i am using `$post->ID`. what would i change `$post->ID` to be in order to work correctly with the rest of my function? any help would be greatly appreciated.
```
$args = array(
'post_type' => 'page',
'posts_per_page' => -1,
'post_parent' => 91,
'order' => 'ASC',
);
$parent = new WP_Query( $args );
if ( $parent->have_posts() ) :
echo '<div class="events_lists_on_page">';
while ( $parent->have_posts() ) : $parent->the_post();
//grab the menu item data
$image_uploaded_meta_id = get_post_meta($post->ID, '_listing_image_id', true);
$image_thumb_url = wp_get_attachment_image_src($image_uploaded_meta_id, 'full');
//grab and save title of post
$title = get_the_title();
//grab and save the link to the post
$link = get_permalink();
//grab content
$the_content = get_the_content();
echo '<div class="element">';
echo '<img src="'. $image_thumb_url[0] .'">';
echo '<div class="text"><p>' . $title .'</p></div>';
echo '<p>'. $the_content .'</p>';
echo '</div>';
endwhile;
echo '</div>';
endif;
``` | Try with `get_the_ID()`
```
$image_uploaded_meta_id = get_post_meta(get_the_ID(), '_listing_image_id', true);
```
`get_the_ID()` is a core Wordpress function that acts directly inside the Wordpress Loop, retrieving the id of the current item being loaded. `$post->id` is not working because the variable `$post` has no scope inside the loop.
Here's the link to the documentation: <https://developer.wordpress.org/reference/functions/get_the_id/> |
270,303 | <p>I created wp-theme, use plugin Custom Post Type UI.</p>
<p>Created sections - <code>Customers</code> and <code>Projects</code>.</p>
<p><a href="https://i.stack.imgur.com/Pj03P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pj03P.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/3KZV1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3KZV1.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/VpUc2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VpUc2.png" alt="enter image description here"></a></p>
<p>In page-projects.php, display list (links) all of customers:</p>
<p><a href="https://i.stack.imgur.com/1xkvk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1xkvk.png" alt="enter image description here"></a></p>
<pre><code>$args = array(
'post_type' => 'customer'
);
$the_query = new WP_Query( $args );
</code></pre>
<p>Im trying to display content from post <code>projects</code> (about customer).
Page <code>single-customer.php</code> display content from <code>customers</code>, but I need post from <code>projects</code>.</p>
<p><a href="https://i.stack.imgur.com/o2Pl5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o2Pl5.png" alt="enter image description here"></a></p>
<p>How get this post content? Its possible?</p>
<p><strong>UPD</strong></p>
<p>code in <code>single-customer.php</code>:</p>
<pre><code> `<div class="page-head text-center">
<div class="container">
<h1 class="page-head_title"><?php the_title(); ?></h1>
<p><?php the_subtitle(); ?></p>
</div>
</div>
<?php
// This is for projects posts
$args = array(
'post_type' => 'project'
);
$the_query = new WP_Query( $args );
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
// loop here
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile;
wp_reset_postdata();
else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>`
</code></pre>
<p><strong>UPD</strong></p>
<p>if i use this code <code><?php acf_form(); ?></code> its display content which i need, but its display all textarea and inputs of wp-admin panel. if i use <code><?php the_field('project-sections'); ?></code> - its display <code>Array, Array, Array, Array</code></p>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120398/"
]
| I created wp-theme, use plugin Custom Post Type UI.
Created sections - `Customers` and `Projects`.
[](https://i.stack.imgur.com/Pj03P.png)
[](https://i.stack.imgur.com/3KZV1.png)
[](https://i.stack.imgur.com/VpUc2.png)
In page-projects.php, display list (links) all of customers:
[](https://i.stack.imgur.com/1xkvk.png)
```
$args = array(
'post_type' => 'customer'
);
$the_query = new WP_Query( $args );
```
Im trying to display content from post `projects` (about customer).
Page `single-customer.php` display content from `customers`, but I need post from `projects`.
[](https://i.stack.imgur.com/o2Pl5.png)
How get this post content? Its possible?
**UPD**
code in `single-customer.php`:
```
`<div class="page-head text-center">
<div class="container">
<h1 class="page-head_title"><?php the_title(); ?></h1>
<p><?php the_subtitle(); ?></p>
</div>
</div>
<?php
// This is for projects posts
$args = array(
'post_type' => 'project'
);
$the_query = new WP_Query( $args );
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
// loop here
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile;
wp_reset_postdata();
else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>`
```
**UPD**
if i use this code `<?php acf_form(); ?>` its display content which i need, but its display all textarea and inputs of wp-admin panel. if i use `<?php the_field('project-sections'); ?>` - its display `Array, Array, Array, Array` | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,304 | <p>I would like to add a CSS class to the body if a visitor goes to the second or third etc. page of the website. Or vice-versa: add a class only on the first visited page. The goal is that I can distinguish the first visited page. </p>
<p>Do you have any idea how can I solve this? Javascript? WP_SESSIONS?</p>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48882/"
]
| I would like to add a CSS class to the body if a visitor goes to the second or third etc. page of the website. Or vice-versa: add a class only on the first visited page. The goal is that I can distinguish the first visited page.
Do you have any idea how can I solve this? Javascript? WP\_SESSIONS? | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,309 | <p>So i am developing a hybrid app using cordova and jquery mobile. I need to login to a wordpress blog site and create a new post in my hybrid app. I am using JSON Api plugin(<a href="https://wordpress.org/plugins/json-api/" rel="nofollow noreferrer">https://wordpress.org/plugins/json-api/</a>) to perform AJAX post. The issue is when i try to create a new post using the <code>create_post method</code>,i get the following error:</p>
<blockquote>
<p><strong>POST http//some_localhost_ip/wordpress/api/create_post/? 403(Forbidden)</strong></p>
</blockquote>
<p>I have also used JSON Api user plugin (<a href="https://wordpress.org/plugins/json-api-user/" rel="nofollow noreferrer">https://wordpress.org/plugins/json-api-user/</a>) for user authentication where in i am using the <code>generate_auth_cookie</code> method.</p>
<p><strong><em>authentication-controller.js</em></strong></p>
<pre><code>$.ajax({
url: SERVER_URL + "/api/get_nonce/?controller=user&method=generate_auth_cookie",
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
crossDomain: true,
cache: true,
success: function(result) {
if (result.status == "ok") {
var url = SERVER_URL + "/api/user/generate_auth_cookie/?"
var dataString = {};
dataString["nonce"] = result.nonce;
dataString["username"] = username;
dataString["password"] = password;
if (!checkBox.is(':checked')) {
dataString["seconds"] = SESSION_TIMEOUT;
}
dataString["insecure"] = "cool"; // remove this if SSL certificate is installed and the url is HTTPS
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
data: dataString,
crossDomain: true,
cache: false,
success: function(result) {
if (result.status == "ok") {
window.localStorage.setItem("USERDATA", JSON.stringify(result.user));
window.localStorage.setItem("USERCOOKIE", result.cookie);
console
switch (result.user.role[0]) {
case "subscriber":
$.mobile.navigate("#page-subscriber-allposts");
break;
case "author":
$.mobile.navigate("#page-author-allposts");
break;
case "editor":
$.mobile.navigate("#page-editor-allposts");
break;
default:
$.mobile.navigate("#page-contributor-allposts");
break;
}
} else {
navigator.notification.alert(result.error, function doNothing() {}, "ERROR!", "OK");
}
return;
},
error: function(error) {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
} else {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
</code></pre>
<p><strong><em>workflow-controller.js</em></strong></p>
<pre><code>var url = SERVER_URL;
if (null != postId && typeof postId != "undefined") {
url += "/api/get_nonce/?controller=posts&method=update_post";
} else {
url += "/api/get_nonce/?controller=posts&method=create_post";
}
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
crossDomain: true,
cache: false,
success: function(result) {
alert(JSON.stringify(result));
if (result.status == "ok") {
var dataString = {};
if (null != postId && typeof postId != "undefined") {
url = SERVER_URL + "/api/update_post/?";
} else {
url = SERVER_URL + "/api/create_post/?";
dataString["post_id"] = postId;
}
dataString["nonce"] = result.nonce;
dataString["cookie"] = window.localStorage.getItem("USERCOOKIE");
dataString["author"] = author;
dataString["title"] = title;
dataString["content"] = news;
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
data: dataString,
crossDomain: true,
cache: false,
success: function(result) {
alert(JSON.stringify(result));
if (result.status == "ok") {
navigator.notification.alert("Your post was successfully submitted and is pending for review", function doNothing() {}, "Hurray!!", "Ok");
$.mobile.navigate("#page-author-allposts");
return;
}else {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
}else {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
</code></pre>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270309",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121899/"
]
| So i am developing a hybrid app using cordova and jquery mobile. I need to login to a wordpress blog site and create a new post in my hybrid app. I am using JSON Api plugin(<https://wordpress.org/plugins/json-api/>) to perform AJAX post. The issue is when i try to create a new post using the `create_post method`,i get the following error:
>
> **POST http//some\_localhost\_ip/wordpress/api/create\_post/? 403(Forbidden)**
>
>
>
I have also used JSON Api user plugin (<https://wordpress.org/plugins/json-api-user/>) for user authentication where in i am using the `generate_auth_cookie` method.
***authentication-controller.js***
```
$.ajax({
url: SERVER_URL + "/api/get_nonce/?controller=user&method=generate_auth_cookie",
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
crossDomain: true,
cache: true,
success: function(result) {
if (result.status == "ok") {
var url = SERVER_URL + "/api/user/generate_auth_cookie/?"
var dataString = {};
dataString["nonce"] = result.nonce;
dataString["username"] = username;
dataString["password"] = password;
if (!checkBox.is(':checked')) {
dataString["seconds"] = SESSION_TIMEOUT;
}
dataString["insecure"] = "cool"; // remove this if SSL certificate is installed and the url is HTTPS
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
data: dataString,
crossDomain: true,
cache: false,
success: function(result) {
if (result.status == "ok") {
window.localStorage.setItem("USERDATA", JSON.stringify(result.user));
window.localStorage.setItem("USERCOOKIE", result.cookie);
console
switch (result.user.role[0]) {
case "subscriber":
$.mobile.navigate("#page-subscriber-allposts");
break;
case "author":
$.mobile.navigate("#page-author-allposts");
break;
case "editor":
$.mobile.navigate("#page-editor-allposts");
break;
default:
$.mobile.navigate("#page-contributor-allposts");
break;
}
} else {
navigator.notification.alert(result.error, function doNothing() {}, "ERROR!", "OK");
}
return;
},
error: function(error) {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
} else {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
```
***workflow-controller.js***
```
var url = SERVER_URL;
if (null != postId && typeof postId != "undefined") {
url += "/api/get_nonce/?controller=posts&method=update_post";
} else {
url += "/api/get_nonce/?controller=posts&method=create_post";
}
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
crossDomain: true,
cache: false,
success: function(result) {
alert(JSON.stringify(result));
if (result.status == "ok") {
var dataString = {};
if (null != postId && typeof postId != "undefined") {
url = SERVER_URL + "/api/update_post/?";
} else {
url = SERVER_URL + "/api/create_post/?";
dataString["post_id"] = postId;
}
dataString["nonce"] = result.nonce;
dataString["cookie"] = window.localStorage.getItem("USERCOOKIE");
dataString["author"] = author;
dataString["title"] = title;
dataString["content"] = news;
$.ajax({
url: url,
type: "POST",
headers: {
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
},
data: dataString,
crossDomain: true,
cache: false,
success: function(result) {
alert(JSON.stringify(result));
if (result.status == "ok") {
navigator.notification.alert("Your post was successfully submitted and is pending for review", function doNothing() {}, "Hurray!!", "Ok");
$.mobile.navigate("#page-author-allposts");
return;
}else {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
}else {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
},
error: function(error) {
navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
return;
}
});
``` | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,328 | <p>How can I send username and password of new registration to admin using email.</p>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110592/"
]
| How can I send username and password of new registration to admin using email. | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,366 | <p>I am an experienced PHP developer, but new to WordPress. I created a site and added some custom JavaScript, CSS, and a number of shortcodes. My CSS was just added to style.css (The default when I clicked on Appearance->Editor in the sidebar) and the hooks to my JavaScript as well as my shortcodes were in my theme's functions.php file.</p>
<p>Naturally, the theme updated and all my changes were wiped. Thankfully I had backups saved, so I was able to restore my custom code, but I really want all my custom code to be completely independent of the theme. What's the proper way to handle shortcodes, css, and script/style enqueing so that theme changes won't remove them?</p>
<p>I found a number of blogs recommending using child themes, but as I understand it that's not truly theme agnostic, for lack of a better term. I want my shortcodes and JS libraries to remain in place no matter if the theme updates, wordpress updates, or I change themes completely.</p>
<p>I also made a small update to my theme's header.php file (I wanted the ability to add a quote to my site, above the menu items, and reposition where the site logo was displayed) I'm imagining this will be more difficult to maintain since, unlike CSS and shortcodes, it is actually changing the content, not adding to it. Is there any way to protect/maintain changes to a theme's header.php as well?</p>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270366",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121934/"
]
| I am an experienced PHP developer, but new to WordPress. I created a site and added some custom JavaScript, CSS, and a number of shortcodes. My CSS was just added to style.css (The default when I clicked on Appearance->Editor in the sidebar) and the hooks to my JavaScript as well as my shortcodes were in my theme's functions.php file.
Naturally, the theme updated and all my changes were wiped. Thankfully I had backups saved, so I was able to restore my custom code, but I really want all my custom code to be completely independent of the theme. What's the proper way to handle shortcodes, css, and script/style enqueing so that theme changes won't remove them?
I found a number of blogs recommending using child themes, but as I understand it that's not truly theme agnostic, for lack of a better term. I want my shortcodes and JS libraries to remain in place no matter if the theme updates, wordpress updates, or I change themes completely.
I also made a small update to my theme's header.php file (I wanted the ability to add a quote to my site, above the menu items, and reposition where the site logo was displayed) I'm imagining this will be more difficult to maintain since, unlike CSS and shortcodes, it is actually changing the content, not adding to it. Is there any way to protect/maintain changes to a theme's header.php as well? | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,376 | <p>I am running WP Multisite in version 4.8</p>
<p>I have a site in the network that lost the visual editor toolbar a ways back (not exactly sure when it disappeared). When you go to Text view mode the content and markup is entirely visible. When you go to Visual view mode the content is there but white text on white background. Plus, the visual editor toolbar is missing all together.</p>
<p>I am running 18 plugins on this site -- none of which are TinyMCE, etc.</p>
<p>I have done all of the following:</p>
<ul>
<li>I uninstalled every single WordPress plugin in the site to test the visual editor -- no success the editor is not present</li>
<li>I uninstalled the custom WordPress theme and replaced with the WP Twenty Seventeen theme to test the visual editor -- no success the editor is not present</li>
<li>Googled the issue (there are numerous references and posts out there specific to the issue) and tried most all of theme to test the visual editor -- no success the editor is not present</li>
<li>added <code>define('CONCATENATE_SCRIPTS', false);</code> to the beginning of my <code>wp_config.php</code> file to test the visual editor -- no success the editor is not present</li>
<li>Logged into a number of other sites in my WordPress network to test the visual editor -- success, the editor is present</li>
</ul>
<p>Anyone have this same issue?</p>
| [
{
"answer_id": 270315,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>Multiple loops in the same page </p>\n\n<pre><code><?php\n// this is for customer posts\n$args = array(\n 'post_type' => 'customer'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n <?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n\n<?php\n // This is for projects posts\n$args = array(\n 'post_type' => 'projects'\n );\n$the_query = new WP_Query( $args );\n ?>\n <?php if ($the_query->have_posts()) : ?>\n <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>\n<?php // loop here\n the_title(); \nthe_content(); ?>\n<?php endwhile; \n wp_reset_postdata();\n else : ?>\n <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n <?php endif; ?>\n</code></pre>\n\n<p>You can also mix the posts like this </p>\n\n<pre><code>'post_type' => array('customer', 'projects'),\n</code></pre>\n"
},
{
"answer_id": 270534,
"author": "siberian",
"author_id": 120398,
"author_profile": "https://wordpress.stackexchange.com/users/120398",
"pm_score": 1,
"selected": true,
"text": "<p>i found solution:</p>\n\n<pre><code><?php if( have_rows('project-sections') ): ?>\n <?php $i = 0; ?>\n\n <?php while( have_rows('project-sections') ): the_row(); ?>\n\n <section class=\"<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>\">\n <div class=\"container\">\n <h2 class=\"page-head_sub-title\"><?php the_sub_field('project-sections-title'); ?></h2>\n <?php the_sub_field('project-sections-description'); ?>\n </div>\n </section>\n\n <?php $i++; ?>\n\n <?php endwhile; ?>\n\n <?php endif; ?>\n</code></pre>\n\n<p>Need to use </p>\n\n<p><code><?php the_sub_field('name-sub-field'); ?></code> </p>\n\n<p>inside </p>\n\n<p><code><?php while( have_rows('name-field') ): the_row(); ?></code></p>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270376",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121949/"
]
| I am running WP Multisite in version 4.8
I have a site in the network that lost the visual editor toolbar a ways back (not exactly sure when it disappeared). When you go to Text view mode the content and markup is entirely visible. When you go to Visual view mode the content is there but white text on white background. Plus, the visual editor toolbar is missing all together.
I am running 18 plugins on this site -- none of which are TinyMCE, etc.
I have done all of the following:
* I uninstalled every single WordPress plugin in the site to test the visual editor -- no success the editor is not present
* I uninstalled the custom WordPress theme and replaced with the WP Twenty Seventeen theme to test the visual editor -- no success the editor is not present
* Googled the issue (there are numerous references and posts out there specific to the issue) and tried most all of theme to test the visual editor -- no success the editor is not present
* added `define('CONCATENATE_SCRIPTS', false);` to the beginning of my `wp_config.php` file to test the visual editor -- no success the editor is not present
* Logged into a number of other sites in my WordPress network to test the visual editor -- success, the editor is present
Anyone have this same issue? | i found solution:
```
<?php if( have_rows('project-sections') ): ?>
<?php $i = 0; ?>
<?php while( have_rows('project-sections') ): the_row(); ?>
<section class="<?php if ($i % 2 == 0) : ?>bg-gray<?php else: ?>bg-white<?php endif; ?>">
<div class="container">
<h2 class="page-head_sub-title"><?php the_sub_field('project-sections-title'); ?></h2>
<?php the_sub_field('project-sections-description'); ?>
</div>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
```
Need to use
`<?php the_sub_field('name-sub-field'); ?>`
inside
`<?php while( have_rows('name-field') ): the_row(); ?>` |
270,383 | <p>On my WordPress site, I am using the human time difference for the post date. If you have a post that was posted <code>59 minutes ago</code> or under it appears as posted <code>1 min ago</code>, <code>5 mins ago</code>, or posted <code>35 mins ago</code>. Is there a way that I can change mins to minutes?</p>
<p>This is the code I have.</p>
<p>
</p>
<pre><code><div class="front-page-date">
<?php
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
?>
</div>
</code></pre>
| [
{
"answer_id": 270385,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 3,
"selected": true,
"text": "<p>You can do:</p>\n\n<pre><code>echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago');\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>The same using filter as suggested:</p>\n\n<pre><code>add_filter('human_time_diff', 'new_human_time_diff', 10, 2);\nfunction new_human_time_diff($from, $to) {\n\n // remove filter to prevent the loop\n remove_filter('human_time_diff', 'new_human_time_diff');\n $timediff = str_replace('mins', 'minutes', human_time_diff($from, $to) . ' ago');\n\n // restore the filter\n add_filter( 'human_time_diff', 'new_human_time_diff', 10, 2);\n\n return $timediff;\n}\n\necho human_time_diff(get_the_time('U'), current_time('timestamp'));\n</code></pre>\n"
},
{
"answer_id": 270464,
"author": "Morgan Estes",
"author_id": 26317,
"author_profile": "https://wordpress.stackexchange.com/users/26317",
"pm_score": 1,
"selected": false,
"text": "<p>This is a good use of the <a href=\"https://developer.wordpress.org/reference/hooks/human_time_diff/\" rel=\"nofollow noreferrer\"><code>human_time_diff</code></a> filter, which lets you use your function call as usual, then changes the \"mins\" to \"minutes\" on the fly. No need to change your existing code or modify filter use; use string replacement in the filter callback after the time diff string is created by core.</p>\n\n<pre><code>function wpse_time_diff_mins( $since, $diff, $from, $to ) { \n return str_replace( 'mins', 'minutes', $since );\n}\n\nadd_filter( 'human_time_diff', 'wpse_time_diff_mins', 10, 4 );\n</code></pre>\n"
}
]
| 2017/06/16 | [
"https://wordpress.stackexchange.com/questions/270383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121640/"
]
| On my WordPress site, I am using the human time difference for the post date. If you have a post that was posted `59 minutes ago` or under it appears as posted `1 min ago`, `5 mins ago`, or posted `35 mins ago`. Is there a way that I can change mins to minutes?
This is the code I have.
```
<div class="front-page-date">
<?php
echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
?>
</div>
``` | You can do:
```
echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago');
```
**Update:**
The same using filter as suggested:
```
add_filter('human_time_diff', 'new_human_time_diff', 10, 2);
function new_human_time_diff($from, $to) {
// remove filter to prevent the loop
remove_filter('human_time_diff', 'new_human_time_diff');
$timediff = str_replace('mins', 'minutes', human_time_diff($from, $to) . ' ago');
// restore the filter
add_filter( 'human_time_diff', 'new_human_time_diff', 10, 2);
return $timediff;
}
echo human_time_diff(get_the_time('U'), current_time('timestamp'));
``` |
270,397 | <p><strong>BOUNTY EDIT :</strong></p>
<p>I have a plugin which does have links similar to below:</p>
<blockquote>
<p>mydomain.com/wp-content/plugins/myplugin/includes/categories.php?c=9</p>
</blockquote>
<p>I want these links to be more SEO friendly and to work like this:</p>
<blockquote>
<p>mydomain.com/wp-content/plugins/myplugin/includes/categories/9/</p>
</blockquote>
<p><strong>SOLUTIONS I HAVE TRIED AND FAILED:</strong></p>
<p>The plugin uses ajax. I tried using <code>add_rewrite_rule</code> as below
My plugin has following function:</p>
<pre><code>add_action( 'init', 'add_alexes_rules' );
function add_alexes_rules() {
add_rewrite_rule('^categories/([0-9]+)/?$', 'categories.php?c=$1', 'top');
flush_rewrite_rules();
}
</code></pre>
<p>and learned that it won't work after a reply from <strong>@Milo</strong>: </p>
<blockquote>
<p>Internal rules should point to index.php</p>
</blockquote>
<p>and tried to edit <code>.htaccess</code> directly but stuck after a reply from <strong>@Deadooshka</strong>: </p>
<blockquote>
<p>WP uses php-server-variables to handle request thru the index.php, so
rule must change that variable.</p>
</blockquote>
<p>So what is the way to achieve this?</p>
<p><strong>EDIT: Jack Johansson's SOLUTION</strong></p>
<p>Created a php file: <code>page-custom.php</code> as below: </p>
<pre><code><?php
/**
* Template Name: My Custom Template
*/
if (is_page_template( 'page-custom.php' ) && isset($_REQUEST['cat'])){
...
}
?>
</code></pre>
<p>Created a page with <code>ID: 281</code> which uses <code>page-custom.php</code> template.</p>
<p>My <code>functions.php</code>: </p>
<pre><code>function my_rewrite_tag() {
add_rewrite_tag('%cat%', '([^&]+)');
}
function my_rewrite_rule() {
add_rewrite_rule('^categories/([^/]*)/?','index.php?page_id=281&cat=$matches[1]','top');
}
add_action('init', 'my_rewrite_tag', 10, 0);
add_action('init', 'my_rewrite_rule', 10, 0);
</code></pre>
<p>Now when I navigate to an example url like the one below</p>
<blockquote>
<p><a href="http://localhost/mydomain/categories/123/" rel="nofollow noreferrer">http://localhost/mydomain/categories/123/</a></p>
</blockquote>
<p>Problem is <code>$_REQUEST['cat']</code> is empty so it never enters to the condition inside <code>page-custom.php</code> </p>
| [
{
"answer_id": 270400,
"author": "Morgan Estes",
"author_id": 26317,
"author_profile": "https://wordpress.stackexchange.com/users/26317",
"pm_score": 1,
"selected": false,
"text": "<p>Rewrite rules expect the new location to go off <code>index.php</code>. If you change it to <code>'index.php?pagename=tisort-tasarla'</code> it should work as long as that page (or post) exists and is published.</p>\n"
},
{
"answer_id": 270524,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>Why don't we create our own template file, and do our stuff there? Here's what I'm going to do:</p>\n\n<ol>\n<li>Create a custom page template</li>\n<li>Call the required plugin's functions inside the page</li>\n<li>Redirect the plugins URLs to the page</li>\n<li>Get the query var and process the request</li>\n</ol>\n\n<hr>\n\n<h2> - The page template</h2>\n\n<p>Let's create a simple custom page template. We call it <code>page-custom.php</code>. We will use this page to interact with our plugin.</p>\n\n<pre><code><?php\n/**\n * Template Name: My Custom Template\n */\n // Our function to get the data\n if (function_exists('sample_function')) sample_function();\n?>\n</code></pre>\n\n<p>We also create a page in the back-end, its slug is <code>/my-custom-page/</code> and its ID is <code>123</code>.</p>\n\n<h2>- The rewrite rules</h2>\n\n<p>Now let's check if we are on that page and redirect the data to it.</p>\n\n<pre><code>function my_rewrite_tag() {\n add_rewrite_tag('%cat%', '([^&]+)');\n}\nfunction wallpaperinho_subcat_rewrite_rule() {\n add_rewrite_rule('^categories/([^/]*)/?','index.php?page_id=123&cat=$matches[1]','top');\n}\nadd_action('init', 'my_rewrite_tag', 10, 0);\nadd_action('init', 'my_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>What does this piece of code do? It checks if we are visiting <code>/categories/321/</code> and redirects it to our page. Now we have the data we need. Let's check the template.</p>\n\n<h2>- The conditional for template</h2>\n\n<p>We check if we are on <code>page-custom.php</code> and return our data to the page.</p>\n\n<pre><code>if (is_page_template( 'templates/about.php' ) && isset($_REQUEST['cat'])){\n function sample_function() { \n $c = $_REQUEST['cat'];\n // We have the c value, call the internal plugin's functions and return its value to the page\n return $data;\n }\n}\n</code></pre>\n\n<p>This serves as an example, to create our own template and use the redirects to make it look like whatever we want. It can and needs to be changed to fit your needs.</p>\n"
}
]
| 2017/06/17 | [
"https://wordpress.stackexchange.com/questions/270397",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112778/"
]
| **BOUNTY EDIT :**
I have a plugin which does have links similar to below:
>
> mydomain.com/wp-content/plugins/myplugin/includes/categories.php?c=9
>
>
>
I want these links to be more SEO friendly and to work like this:
>
> mydomain.com/wp-content/plugins/myplugin/includes/categories/9/
>
>
>
**SOLUTIONS I HAVE TRIED AND FAILED:**
The plugin uses ajax. I tried using `add_rewrite_rule` as below
My plugin has following function:
```
add_action( 'init', 'add_alexes_rules' );
function add_alexes_rules() {
add_rewrite_rule('^categories/([0-9]+)/?$', 'categories.php?c=$1', 'top');
flush_rewrite_rules();
}
```
and learned that it won't work after a reply from **@Milo**:
>
> Internal rules should point to index.php
>
>
>
and tried to edit `.htaccess` directly but stuck after a reply from **@Deadooshka**:
>
> WP uses php-server-variables to handle request thru the index.php, so
> rule must change that variable.
>
>
>
So what is the way to achieve this?
**EDIT: Jack Johansson's SOLUTION**
Created a php file: `page-custom.php` as below:
```
<?php
/**
* Template Name: My Custom Template
*/
if (is_page_template( 'page-custom.php' ) && isset($_REQUEST['cat'])){
...
}
?>
```
Created a page with `ID: 281` which uses `page-custom.php` template.
My `functions.php`:
```
function my_rewrite_tag() {
add_rewrite_tag('%cat%', '([^&]+)');
}
function my_rewrite_rule() {
add_rewrite_rule('^categories/([^/]*)/?','index.php?page_id=281&cat=$matches[1]','top');
}
add_action('init', 'my_rewrite_tag', 10, 0);
add_action('init', 'my_rewrite_rule', 10, 0);
```
Now when I navigate to an example url like the one below
>
> <http://localhost/mydomain/categories/123/>
>
>
>
Problem is `$_REQUEST['cat']` is empty so it never enters to the condition inside `page-custom.php` | Why don't we create our own template file, and do our stuff there? Here's what I'm going to do:
1. Create a custom page template
2. Call the required plugin's functions inside the page
3. Redirect the plugins URLs to the page
4. Get the query var and process the request
---
- The page template
--------------------
Let's create a simple custom page template. We call it `page-custom.php`. We will use this page to interact with our plugin.
```
<?php
/**
* Template Name: My Custom Template
*/
// Our function to get the data
if (function_exists('sample_function')) sample_function();
?>
```
We also create a page in the back-end, its slug is `/my-custom-page/` and its ID is `123`.
- The rewrite rules
-------------------
Now let's check if we are on that page and redirect the data to it.
```
function my_rewrite_tag() {
add_rewrite_tag('%cat%', '([^&]+)');
}
function wallpaperinho_subcat_rewrite_rule() {
add_rewrite_rule('^categories/([^/]*)/?','index.php?page_id=123&cat=$matches[1]','top');
}
add_action('init', 'my_rewrite_tag', 10, 0);
add_action('init', 'my_rewrite_rule', 10, 0);
```
What does this piece of code do? It checks if we are visiting `/categories/321/` and redirects it to our page. Now we have the data we need. Let's check the template.
- The conditional for template
------------------------------
We check if we are on `page-custom.php` and return our data to the page.
```
if (is_page_template( 'templates/about.php' ) && isset($_REQUEST['cat'])){
function sample_function() {
$c = $_REQUEST['cat'];
// We have the c value, call the internal plugin's functions and return its value to the page
return $data;
}
}
```
This serves as an example, to create our own template and use the redirects to make it look like whatever we want. It can and needs to be changed to fit your needs. |
270,405 | <p>I've got a shortcode working to return tags that are used on a particular post but can't figure out how to return the description with it.</p>
<pre><code>function returnpost_tags(){
return get_the_tag_list('',', ',' ');
}
add_shortcode('post-tags', 'returnpost_tags');
</code></pre>
<p>I tried </p>
<pre><code>return get_the_tag_list('',', ',' $description');
</code></pre>
<p>but obviously something not right</p>
<p>as a bonus I'd like to alternatively as a separate function return the list with description but without the links to the tags archive which is the normal behavior</p>
<p>thanks for the help</p>
| [
{
"answer_id": 270408,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to work with the tags, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_tags\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code></a> in the loop instead:</p>\n\n<pre><code>function my_tag_shortcode(){\n // Get a list of tags\n $tags = get_the_tags();\n $data ='';\n // Run a loop to output the data\n foreach ($tags as $tag) { \n $data .= '<a href=\"'.get_tag_link($tag->term_id).'\">'. $tag->name .'</a><span>'. $tag->description .'</span>';\n }\n return $data;\n}\n</code></pre>\n\n<p>Now, you have the tag's name, ID, description, and more. Choose whatever you want, based on your needs.</p>\n"
},
{
"answer_id": 270410,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>This is how you can loop with custom taxonomy. </p>\n\n<pre><code>function returnpost_tags(){\n// get tags by post ID \n$post_ID = get_the_ID();\n// here, you can add any custom tag\n$terms = get_the_terms( $post_ID , 'post_tag' ); \necho '<ul>';\n\nforeach ( $terms as $term ) {\n\n// The $term is an object, so we don't need to specify the $taxonomy.\n$term_link = get_term_link( $term );\n$term_ID = $term->term_id;\n// If there was an error, continue to the next term.\nif ( is_wp_error( $term_link ) ) {\n continue;\n}\n\necho '<li><a href=\"' . esc_url( $term_link ) . '\">' . $term->name . '</a></li>';\necho term_description($term_ID);\n\n // another option\n // echo '<p>' . $term->description . '</p>';\n\n}\n\necho '</ul>';\n}\nadd_shortcode('post-tags', 'returnpost_tags');\n</code></pre>\n\n<p>You can replace <strong>post_tag</strong> with your custom taxonomy </p>\n\n<pre><code>$terms = get_terms( 'post_tag' ); \n</code></pre>\n\n<p>To get tag's description, you can use one of the below method.</p>\n\n<pre><code> echo $term->description;\n</code></pre>\n\n<p>or</p>\n\n<pre><code> echo term_description($term->term_id);\n</code></pre>\n"
}
]
| 2017/06/17 | [
"https://wordpress.stackexchange.com/questions/270405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121961/"
]
| I've got a shortcode working to return tags that are used on a particular post but can't figure out how to return the description with it.
```
function returnpost_tags(){
return get_the_tag_list('',', ',' ');
}
add_shortcode('post-tags', 'returnpost_tags');
```
I tried
```
return get_the_tag_list('',', ',' $description');
```
but obviously something not right
as a bonus I'd like to alternatively as a separate function return the list with description but without the links to the tags archive which is the normal behavior
thanks for the help | This is how you can loop with custom taxonomy.
```
function returnpost_tags(){
// get tags by post ID
$post_ID = get_the_ID();
// here, you can add any custom tag
$terms = get_the_terms( $post_ID , 'post_tag' );
echo '<ul>';
foreach ( $terms as $term ) {
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link( $term );
$term_ID = $term->term_id;
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
echo term_description($term_ID);
// another option
// echo '<p>' . $term->description . '</p>';
}
echo '</ul>';
}
add_shortcode('post-tags', 'returnpost_tags');
```
You can replace **post\_tag** with your custom taxonomy
```
$terms = get_terms( 'post_tag' );
```
To get tag's description, you can use one of the below method.
```
echo $term->description;
```
or
```
echo term_description($term->term_id);
``` |
270,416 | <p>I'm using the 2017 theme. I'm trying to set up a simple website where a user is able to easily add a photo with accompanying text (description).
The uploaded content should appear on one page where the photo will be in one column and the description (not caption - it's longer than just a caption) will be displayed on the 2nd column.</p>
<p>Please advise.</p>
| [
{
"answer_id": 270408,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to work with the tags, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_tags\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code></a> in the loop instead:</p>\n\n<pre><code>function my_tag_shortcode(){\n // Get a list of tags\n $tags = get_the_tags();\n $data ='';\n // Run a loop to output the data\n foreach ($tags as $tag) { \n $data .= '<a href=\"'.get_tag_link($tag->term_id).'\">'. $tag->name .'</a><span>'. $tag->description .'</span>';\n }\n return $data;\n}\n</code></pre>\n\n<p>Now, you have the tag's name, ID, description, and more. Choose whatever you want, based on your needs.</p>\n"
},
{
"answer_id": 270410,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>This is how you can loop with custom taxonomy. </p>\n\n<pre><code>function returnpost_tags(){\n// get tags by post ID \n$post_ID = get_the_ID();\n// here, you can add any custom tag\n$terms = get_the_terms( $post_ID , 'post_tag' ); \necho '<ul>';\n\nforeach ( $terms as $term ) {\n\n// The $term is an object, so we don't need to specify the $taxonomy.\n$term_link = get_term_link( $term );\n$term_ID = $term->term_id;\n// If there was an error, continue to the next term.\nif ( is_wp_error( $term_link ) ) {\n continue;\n}\n\necho '<li><a href=\"' . esc_url( $term_link ) . '\">' . $term->name . '</a></li>';\necho term_description($term_ID);\n\n // another option\n // echo '<p>' . $term->description . '</p>';\n\n}\n\necho '</ul>';\n}\nadd_shortcode('post-tags', 'returnpost_tags');\n</code></pre>\n\n<p>You can replace <strong>post_tag</strong> with your custom taxonomy </p>\n\n<pre><code>$terms = get_terms( 'post_tag' ); \n</code></pre>\n\n<p>To get tag's description, you can use one of the below method.</p>\n\n<pre><code> echo $term->description;\n</code></pre>\n\n<p>or</p>\n\n<pre><code> echo term_description($term->term_id);\n</code></pre>\n"
}
]
| 2017/06/17 | [
"https://wordpress.stackexchange.com/questions/270416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121978/"
]
| I'm using the 2017 theme. I'm trying to set up a simple website where a user is able to easily add a photo with accompanying text (description).
The uploaded content should appear on one page where the photo will be in one column and the description (not caption - it's longer than just a caption) will be displayed on the 2nd column.
Please advise. | This is how you can loop with custom taxonomy.
```
function returnpost_tags(){
// get tags by post ID
$post_ID = get_the_ID();
// here, you can add any custom tag
$terms = get_the_terms( $post_ID , 'post_tag' );
echo '<ul>';
foreach ( $terms as $term ) {
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link( $term );
$term_ID = $term->term_id;
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
echo term_description($term_ID);
// another option
// echo '<p>' . $term->description . '</p>';
}
echo '</ul>';
}
add_shortcode('post-tags', 'returnpost_tags');
```
You can replace **post\_tag** with your custom taxonomy
```
$terms = get_terms( 'post_tag' );
```
To get tag's description, you can use one of the below method.
```
echo $term->description;
```
or
```
echo term_description($term->term_id);
``` |
270,427 | <p>I have a problem with my shop columns in WooCommerce.</p>
<p>I would like to display 4 columns in my shop but unfortunately there is just 3 columns.</p>
<p>I use the Storefront theme for my shop, so I have looked the <code>storefront-template-fonction.php</code> file and the different <code>apply_filters</code> are setting up on 'columns'=>4.</p>
<p>Exemple:</p>
<pre><code>$args = apply_filters( ‘storefront_popular_products_args’, array(
‘limit’ => 4,
‘columns’ => 4,
‘title’ => __( ‘Fan Favorites’, ‘storefront’ ),
) );
</code></pre>
<p>The only "solution" I have found is to used the shortcode <code>[recent_products per_page="12" columns="4"]</code>.</p>
<p>But with that, I have another problem, I have the 4 columns that I wanted with my products but the 3 previous columns displayed below too.</p>
<p>I work in Local with an Uwamp server and the last update of WordPress, Storefront and WooCommerce.</p>
<p>I hope there is somebody who can help me.</p>
| [
{
"answer_id": 270408,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to work with the tags, you can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_tags\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code></a> in the loop instead:</p>\n\n<pre><code>function my_tag_shortcode(){\n // Get a list of tags\n $tags = get_the_tags();\n $data ='';\n // Run a loop to output the data\n foreach ($tags as $tag) { \n $data .= '<a href=\"'.get_tag_link($tag->term_id).'\">'. $tag->name .'</a><span>'. $tag->description .'</span>';\n }\n return $data;\n}\n</code></pre>\n\n<p>Now, you have the tag's name, ID, description, and more. Choose whatever you want, based on your needs.</p>\n"
},
{
"answer_id": 270410,
"author": "Ronald",
"author_id": 27469,
"author_profile": "https://wordpress.stackexchange.com/users/27469",
"pm_score": 1,
"selected": false,
"text": "<p>This is how you can loop with custom taxonomy. </p>\n\n<pre><code>function returnpost_tags(){\n// get tags by post ID \n$post_ID = get_the_ID();\n// here, you can add any custom tag\n$terms = get_the_terms( $post_ID , 'post_tag' ); \necho '<ul>';\n\nforeach ( $terms as $term ) {\n\n// The $term is an object, so we don't need to specify the $taxonomy.\n$term_link = get_term_link( $term );\n$term_ID = $term->term_id;\n// If there was an error, continue to the next term.\nif ( is_wp_error( $term_link ) ) {\n continue;\n}\n\necho '<li><a href=\"' . esc_url( $term_link ) . '\">' . $term->name . '</a></li>';\necho term_description($term_ID);\n\n // another option\n // echo '<p>' . $term->description . '</p>';\n\n}\n\necho '</ul>';\n}\nadd_shortcode('post-tags', 'returnpost_tags');\n</code></pre>\n\n<p>You can replace <strong>post_tag</strong> with your custom taxonomy </p>\n\n<pre><code>$terms = get_terms( 'post_tag' ); \n</code></pre>\n\n<p>To get tag's description, you can use one of the below method.</p>\n\n<pre><code> echo $term->description;\n</code></pre>\n\n<p>or</p>\n\n<pre><code> echo term_description($term->term_id);\n</code></pre>\n"
}
]
| 2017/06/17 | [
"https://wordpress.stackexchange.com/questions/270427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121985/"
]
| I have a problem with my shop columns in WooCommerce.
I would like to display 4 columns in my shop but unfortunately there is just 3 columns.
I use the Storefront theme for my shop, so I have looked the `storefront-template-fonction.php` file and the different `apply_filters` are setting up on 'columns'=>4.
Exemple:
```
$args = apply_filters( ‘storefront_popular_products_args’, array(
‘limit’ => 4,
‘columns’ => 4,
‘title’ => __( ‘Fan Favorites’, ‘storefront’ ),
) );
```
The only "solution" I have found is to used the shortcode `[recent_products per_page="12" columns="4"]`.
But with that, I have another problem, I have the 4 columns that I wanted with my products but the 3 previous columns displayed below too.
I work in Local with an Uwamp server and the last update of WordPress, Storefront and WooCommerce.
I hope there is somebody who can help me. | This is how you can loop with custom taxonomy.
```
function returnpost_tags(){
// get tags by post ID
$post_ID = get_the_ID();
// here, you can add any custom tag
$terms = get_the_terms( $post_ID , 'post_tag' );
echo '<ul>';
foreach ( $terms as $term ) {
// The $term is an object, so we don't need to specify the $taxonomy.
$term_link = get_term_link( $term );
$term_ID = $term->term_id;
// If there was an error, continue to the next term.
if ( is_wp_error( $term_link ) ) {
continue;
}
echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
echo term_description($term_ID);
// another option
// echo '<p>' . $term->description . '</p>';
}
echo '</ul>';
}
add_shortcode('post-tags', 'returnpost_tags');
```
You can replace **post\_tag** with your custom taxonomy
```
$terms = get_terms( 'post_tag' );
```
To get tag's description, you can use one of the below method.
```
echo $term->description;
```
or
```
echo term_description($term->term_id);
``` |
270,446 | <p>I am trying to set up a featured content section of my blog. This will contain two sticky posts.</p>
<p>I have a custom loop which will only display the two sticky posts, in the loop I then get a <code>content-featured.php</code> template which has the structure of the sticky posts.</p>
<p>In the main post div I use <code>post_class()</code>. I know I can pass a value like <code>post_class('featured')</code> but I would like to have a different class name for each sticky post, i.e. <code>featured-0</code>, <code>featured-1</code>.</p>
<p>I have attempted to create a function in <code>functions.php</code>, but as I know very little about PHP, I am struggling to get it to work. Here's what I have:</p>
<pre><code>//add classes to sticky posts
function gwad_sticky_classes( $classes, $class ) {
$sticky = get_option( 'sticky_posts' );
if ( $sticky ) {
$query = new WP_Query( $sticky );
$sticky[0] ='featured-0';
$sticky[1] = 'featured-1';
}
return $classes;
}
add_filter( 'post_class', 'gwad_sticky_classes', 10, 2 );
</code></pre>
<p>As you can see, I don't have a clue what I'm doing, any help would be greatly appreciated.</p>
| [
{
"answer_id": 270450,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a solution that adds additional sticky classes, one for the post ID and one for the sticky post counter.</p>\n\n<pre><code>/**\n * Adds .featured-{$post_id} and .featured-{$sticky_counter}\n * class names to sticky posts.\n *\n * @param array $classes An array of post classes.\n * @param array $class An array of additional classes added to the post.\n * @param int $post_id The post ID.\n *\n * @return array\n */\nadd_filter( 'post_class', 'gwad_sticky_classes', 10, 3 ); \nfunction gwad_sticky_classes( $classes, $class, $post_id ) {\n\n // Bail if this is not a sticky post.\n if ( ! is_sticky() ) {\n return $classes;\n }\n\n // Counter for sticky posts.\n static $gwad_sticky_counter = 0;\n\n $classes[] = 'featured-' . $post_id;\n $classes[] = 'featured-' . ++$gwad_sticky_counter; \n\n return $classes;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Here's an alternate version that avoids using the static variable:</p>\n\n<pre><code>add_filter( 'post_class', 'gwad_sticky_classes', 10, 3 ); \nfunction gwad_sticky_classes( $classes, $class, $post_id ) {\n\n // Bail if this is not a sticky post.\n if ( ! is_sticky() ) {\n return $classes;\n }\n\n global $wp_query;\n $classes[] = 'featured-' . $post_id;\n $classes[] = 'featured-' . ( string ) ( $wp_query->current_post + 1 );\n\n return $classes;\n}\n</code></pre>\n"
},
{
"answer_id": 270818,
"author": "ronald",
"author_id": 1331,
"author_profile": "https://wordpress.stackexchange.com/users/1331",
"pm_score": 1,
"selected": false,
"text": "<p>As an alternative, you can do this with straight forward css. The post class will contain the sticky class by default. So in twentyseventeen theme for example, where the loop is in a div \"main\":</p>\n\n<pre><code>#main .sticky:nth-of-type(1) {\n color: red;\n}\n\n#main .sticky:nth-of-type(2) {\n color: blue;\n}\n</code></pre>\n\n<p>will do the trick.</p>\n"
}
]
| 2017/06/17 | [
"https://wordpress.stackexchange.com/questions/270446",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121998/"
]
| I am trying to set up a featured content section of my blog. This will contain two sticky posts.
I have a custom loop which will only display the two sticky posts, in the loop I then get a `content-featured.php` template which has the structure of the sticky posts.
In the main post div I use `post_class()`. I know I can pass a value like `post_class('featured')` but I would like to have a different class name for each sticky post, i.e. `featured-0`, `featured-1`.
I have attempted to create a function in `functions.php`, but as I know very little about PHP, I am struggling to get it to work. Here's what I have:
```
//add classes to sticky posts
function gwad_sticky_classes( $classes, $class ) {
$sticky = get_option( 'sticky_posts' );
if ( $sticky ) {
$query = new WP_Query( $sticky );
$sticky[0] ='featured-0';
$sticky[1] = 'featured-1';
}
return $classes;
}
add_filter( 'post_class', 'gwad_sticky_classes', 10, 2 );
```
As you can see, I don't have a clue what I'm doing, any help would be greatly appreciated. | Here's a solution that adds additional sticky classes, one for the post ID and one for the sticky post counter.
```
/**
* Adds .featured-{$post_id} and .featured-{$sticky_counter}
* class names to sticky posts.
*
* @param array $classes An array of post classes.
* @param array $class An array of additional classes added to the post.
* @param int $post_id The post ID.
*
* @return array
*/
add_filter( 'post_class', 'gwad_sticky_classes', 10, 3 );
function gwad_sticky_classes( $classes, $class, $post_id ) {
// Bail if this is not a sticky post.
if ( ! is_sticky() ) {
return $classes;
}
// Counter for sticky posts.
static $gwad_sticky_counter = 0;
$classes[] = 'featured-' . $post_id;
$classes[] = 'featured-' . ++$gwad_sticky_counter;
return $classes;
}
```
**Edit:** Here's an alternate version that avoids using the static variable:
```
add_filter( 'post_class', 'gwad_sticky_classes', 10, 3 );
function gwad_sticky_classes( $classes, $class, $post_id ) {
// Bail if this is not a sticky post.
if ( ! is_sticky() ) {
return $classes;
}
global $wp_query;
$classes[] = 'featured-' . $post_id;
$classes[] = 'featured-' . ( string ) ( $wp_query->current_post + 1 );
return $classes;
}
``` |
270,523 | <p>i wanted to know if "Alt title" is needed like "Title" for post thumbnails and how can add it in my related post query... i'm using this code to get the post thumbnail:</p>
<pre><code><div class="td-module-thumb">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if (has_post_thumbnail()) {
the_post_thumbnail(array(324,235));
} else {
echo '<img src="' . get_bloginfo('template_directory') . '/images/no-thumb/td_324x235.png" />';
}
?>
</a>
</div>
</code></pre>
| [
{
"answer_id": 270525,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<p>It is necessary to set an <code>alt</code> value for all of your images, in case a browser can not load the image or the visitor is using screen reader.</p>\n\n<p>You have two options. Either use the featured image's caption (which can some times be blank) or use the post's title as <code>alt</code>.</p>\n\n<p>You can get the caption by using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>. Using it is as simple as this:</p>\n\n<pre><code>$alt = get_post_meta ( $image_id, '_wp_attachment_image_alt', true );\necho '<img alt=\"' . esc_html ( $alt ) . '\" src=\"URL HERE\" />';\n</code></pre>\n\n<p>It should be used in the loop though, or be passed the <code>$post</code> object or ID.</p>\n\n<p>The alternative method is to use post's title as <code>alt</code> text. To do so, you can use:</p>\n\n<pre><code>echo '<img alt=\"' . esc_html ( get_the_title() ) . '\" src=\"URL HERE\" />';\n</code></pre>\n\n<p>You can set up a conditional and check if the thumbnail has a caption, and use it instead of post title, if available:</p>\n\n<pre><code>if ( $alt = get_the_post_thumbnail_caption() ) {\n // Nothing to do here\n} else {\n $alt = get_the_title();\n}\n\necho '<img alt=\"' . esc_html ( $alt ) . '\" src=\"URL HERE\"/>\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>If you wish to add the <code>alt</code> attribute directly to <code>get_post_thumbnail()</code>, you can pass it as an array to the function:</p>\n\n<pre><code>the_post_thumbnail( 'thumbnail', [ 'alt' => esc_html ( get_the_title() ) ] ); \n</code></pre>\n"
},
{
"answer_id": 270533,
"author": "Peyman Naeimi",
"author_id": 119779,
"author_profile": "https://wordpress.stackexchange.com/users/119779",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the following code in your WordPress Theme:</p>\n\n<pre><code><div class=\"td-module-thumb\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php if (has_post_thumbnail()) {\n echo '<img src=\"' . the_post_thumbnail_url( array(324,235) ) . '\" alt=\"any thing you want\" title=\"Some Text\" />';\n } else {\n echo '<img src=\"' . get_bloginfo('template_directory') . '/images/no-thumb/td_324x235.png\" alt=\"any thing you want\" title=\"Some Text\" />';\n }\n ?>\n </a>\n</div>\n</code></pre>\n"
},
{
"answer_id": 306119,
"author": "Tom Woodward",
"author_id": 82797,
"author_profile": "https://wordpress.stackexchange.com/users/82797",
"pm_score": 4,
"selected": false,
"text": "<p>This example uses the alt text as it set in the media library. I prefer it because the behavior is more consistent for users who enter alt text using the typical WordPress options. </p>\n\n<pre><code>$thumbnail_id = get_post_thumbnail_id( $post->ID );\n$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); \nthe_post_thumbnail( 'full', array( 'alt' => $alt ) ); ?>\n</code></pre>\n"
},
{
"answer_id": 386218,
"author": "Mohammad Shiralizadeh",
"author_id": 204478,
"author_profile": "https://wordpress.stackexchange.com/users/204478",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest solution is the following code.</p>\n<pre><code>$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );\n$img_alt = get_post_meta ( $thumbnail_id, '_wp_attachment_image_alt', true );\n\necho $img_alt;\n</code></pre>\n<p>Or to complete the code:</p>\n<pre><code>$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );\n$img_alt = get_post_meta ( $thumbnail_id, '_wp_attachment_image_alt', true );\n\nif(! $img_alt){\n $img_alt = get_the_title();\n}\n</code></pre>\n"
}
]
| 2017/06/19 | [
"https://wordpress.stackexchange.com/questions/270523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117100/"
]
| i wanted to know if "Alt title" is needed like "Title" for post thumbnails and how can add it in my related post query... i'm using this code to get the post thumbnail:
```
<div class="td-module-thumb">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php if (has_post_thumbnail()) {
the_post_thumbnail(array(324,235));
} else {
echo '<img src="' . get_bloginfo('template_directory') . '/images/no-thumb/td_324x235.png" />';
}
?>
</a>
</div>
``` | It is necessary to set an `alt` value for all of your images, in case a browser can not load the image or the visitor is using screen reader.
You have two options. Either use the featured image's caption (which can some times be blank) or use the post's title as `alt`.
You can get the caption by using [`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/). Using it is as simple as this:
```
$alt = get_post_meta ( $image_id, '_wp_attachment_image_alt', true );
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE" />';
```
It should be used in the loop though, or be passed the `$post` object or ID.
The alternative method is to use post's title as `alt` text. To do so, you can use:
```
echo '<img alt="' . esc_html ( get_the_title() ) . '" src="URL HERE" />';
```
You can set up a conditional and check if the thumbnail has a caption, and use it instead of post title, if available:
```
if ( $alt = get_the_post_thumbnail_caption() ) {
// Nothing to do here
} else {
$alt = get_the_title();
}
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE"/>
```
UPDATE
------
If you wish to add the `alt` attribute directly to `get_post_thumbnail()`, you can pass it as an array to the function:
```
the_post_thumbnail( 'thumbnail', [ 'alt' => esc_html ( get_the_title() ) ] );
``` |
270,578 | <p>I have a custom post status and the issue I have is that the filter option for it that automatically appears above the post listings on the edit.php page of the WP admin shows a total count of all the posts with this status. I want it to show a count that is specific to the user in question.</p>
<p>So for example</p>
<blockquote>
<p>All (1) | Published (0) | Draft (0) | Pending (0) | | Trash (0) | <strong>Awaiting (8)</strong></p>
</blockquote>
<p>That figure of 8 for awaiting is all the posts in the system with the status, yet the user I'm logged in at, if they had no posts set to that status I would want that to appear with zero or to not be visible at all (the default functionality in WP I believe).</p>
<p>I can't see if this is functionality supported by WP but I assume there must be a way as the other totals listed in the filter links ARE user specific.</p>
<p>This is all setup via the simple register_post_status function....</p>
<pre><code>function awaiting_custom_post_status(){
register_post_status( 'awaiting', array(
'label' => _x( 'Changes Awaiting Approval', 'apartments' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Changes Awaiting Approval <span class="count">(%s)</span>', 'Changes Awaiting Approval <span class="count">(%s)</span>' ),
) );
}
add_action( 'init', 'awaiting_custom_post_status' );
</code></pre>
<p>Anyone got any ideas how to modify this count value to be user specific such as the other values are?</p>
| [
{
"answer_id": 270525,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<p>It is necessary to set an <code>alt</code> value for all of your images, in case a browser can not load the image or the visitor is using screen reader.</p>\n\n<p>You have two options. Either use the featured image's caption (which can some times be blank) or use the post's title as <code>alt</code>.</p>\n\n<p>You can get the caption by using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta()</code></a>. Using it is as simple as this:</p>\n\n<pre><code>$alt = get_post_meta ( $image_id, '_wp_attachment_image_alt', true );\necho '<img alt=\"' . esc_html ( $alt ) . '\" src=\"URL HERE\" />';\n</code></pre>\n\n<p>It should be used in the loop though, or be passed the <code>$post</code> object or ID.</p>\n\n<p>The alternative method is to use post's title as <code>alt</code> text. To do so, you can use:</p>\n\n<pre><code>echo '<img alt=\"' . esc_html ( get_the_title() ) . '\" src=\"URL HERE\" />';\n</code></pre>\n\n<p>You can set up a conditional and check if the thumbnail has a caption, and use it instead of post title, if available:</p>\n\n<pre><code>if ( $alt = get_the_post_thumbnail_caption() ) {\n // Nothing to do here\n} else {\n $alt = get_the_title();\n}\n\necho '<img alt=\"' . esc_html ( $alt ) . '\" src=\"URL HERE\"/>\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>If you wish to add the <code>alt</code> attribute directly to <code>get_post_thumbnail()</code>, you can pass it as an array to the function:</p>\n\n<pre><code>the_post_thumbnail( 'thumbnail', [ 'alt' => esc_html ( get_the_title() ) ] ); \n</code></pre>\n"
},
{
"answer_id": 270533,
"author": "Peyman Naeimi",
"author_id": 119779,
"author_profile": "https://wordpress.stackexchange.com/users/119779",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the following code in your WordPress Theme:</p>\n\n<pre><code><div class=\"td-module-thumb\">\n <a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\">\n <?php if (has_post_thumbnail()) {\n echo '<img src=\"' . the_post_thumbnail_url( array(324,235) ) . '\" alt=\"any thing you want\" title=\"Some Text\" />';\n } else {\n echo '<img src=\"' . get_bloginfo('template_directory') . '/images/no-thumb/td_324x235.png\" alt=\"any thing you want\" title=\"Some Text\" />';\n }\n ?>\n </a>\n</div>\n</code></pre>\n"
},
{
"answer_id": 306119,
"author": "Tom Woodward",
"author_id": 82797,
"author_profile": "https://wordpress.stackexchange.com/users/82797",
"pm_score": 4,
"selected": false,
"text": "<p>This example uses the alt text as it set in the media library. I prefer it because the behavior is more consistent for users who enter alt text using the typical WordPress options. </p>\n\n<pre><code>$thumbnail_id = get_post_thumbnail_id( $post->ID );\n$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true); \nthe_post_thumbnail( 'full', array( 'alt' => $alt ) ); ?>\n</code></pre>\n"
},
{
"answer_id": 386218,
"author": "Mohammad Shiralizadeh",
"author_id": 204478,
"author_profile": "https://wordpress.stackexchange.com/users/204478",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest solution is the following code.</p>\n<pre><code>$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );\n$img_alt = get_post_meta ( $thumbnail_id, '_wp_attachment_image_alt', true );\n\necho $img_alt;\n</code></pre>\n<p>Or to complete the code:</p>\n<pre><code>$thumbnail_id = get_post_meta( $post->ID, '_thumbnail_id', true );\n$img_alt = get_post_meta ( $thumbnail_id, '_wp_attachment_image_alt', true );\n\nif(! $img_alt){\n $img_alt = get_the_title();\n}\n</code></pre>\n"
}
]
| 2017/06/19 | [
"https://wordpress.stackexchange.com/questions/270578",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28543/"
]
| I have a custom post status and the issue I have is that the filter option for it that automatically appears above the post listings on the edit.php page of the WP admin shows a total count of all the posts with this status. I want it to show a count that is specific to the user in question.
So for example
>
> All (1) | Published (0) | Draft (0) | Pending (0) | | Trash (0) | **Awaiting (8)**
>
>
>
That figure of 8 for awaiting is all the posts in the system with the status, yet the user I'm logged in at, if they had no posts set to that status I would want that to appear with zero or to not be visible at all (the default functionality in WP I believe).
I can't see if this is functionality supported by WP but I assume there must be a way as the other totals listed in the filter links ARE user specific.
This is all setup via the simple register\_post\_status function....
```
function awaiting_custom_post_status(){
register_post_status( 'awaiting', array(
'label' => _x( 'Changes Awaiting Approval', 'apartments' ),
'public' => true,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'Changes Awaiting Approval <span class="count">(%s)</span>', 'Changes Awaiting Approval <span class="count">(%s)</span>' ),
) );
}
add_action( 'init', 'awaiting_custom_post_status' );
```
Anyone got any ideas how to modify this count value to be user specific such as the other values are? | It is necessary to set an `alt` value for all of your images, in case a browser can not load the image or the visitor is using screen reader.
You have two options. Either use the featured image's caption (which can some times be blank) or use the post's title as `alt`.
You can get the caption by using [`get_post_meta()`](https://developer.wordpress.org/reference/functions/get_post_meta/). Using it is as simple as this:
```
$alt = get_post_meta ( $image_id, '_wp_attachment_image_alt', true );
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE" />';
```
It should be used in the loop though, or be passed the `$post` object or ID.
The alternative method is to use post's title as `alt` text. To do so, you can use:
```
echo '<img alt="' . esc_html ( get_the_title() ) . '" src="URL HERE" />';
```
You can set up a conditional and check if the thumbnail has a caption, and use it instead of post title, if available:
```
if ( $alt = get_the_post_thumbnail_caption() ) {
// Nothing to do here
} else {
$alt = get_the_title();
}
echo '<img alt="' . esc_html ( $alt ) . '" src="URL HERE"/>
```
UPDATE
------
If you wish to add the `alt` attribute directly to `get_post_thumbnail()`, you can pass it as an array to the function:
```
the_post_thumbnail( 'thumbnail', [ 'alt' => esc_html ( get_the_title() ) ] );
``` |
270,579 | <p>Is there anyway at all to get the title of a widget from the widget id? The post title can be used by using </p>
<pre><code>get_the_title()
</code></pre>
<p>Is there a way to get the title for a widget using the same kind or function?</p>
| [
{
"answer_id": 270673,
"author": "dbeja",
"author_id": 9585,
"author_profile": "https://wordpress.stackexchange.com/users/9585",
"pm_score": 2,
"selected": false,
"text": "<p>You can get the widget name from the widget id with this:</p>\n\n<pre><code><?php\n global $wp_registered_widgets;\n $id = 'recent-comments-1'; // example\n if ( isset($wp_registered_widgets[$id]['name']) ) {\n echo $wp_registered_widgets[$id]['name'];\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 353753,
"author": "Jörn Lund",
"author_id": 35723,
"author_profile": "https://wordpress.stackexchange.com/users/35723",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me in the <code>dynamic_sidebar_params</code>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Get Widget instance title or widget name as a fallback.\n * Returns empty widget titles too.\n *\n * @param string $widget_id\n * @return string Widget title or widget name\n */\nfunction get_widget_title( $widget_id ) {\n\n global $wp_registered_widgets;\n\n // get instance\n $instance = $wp_registered_widgets[$widget_id]['callback'][0];\n // @see https://developer.wordpress.org/reference/classes/wp_widget/get_settings/\n $settings = $instance->get_settings();\n\n // fallback 1 – widget number can't be found\n if ( isset( $wp_registered_widgets[$widget_id]['params'][0]['number'] ) ) {\n $num = $wp_registered_widgets[$widget_id]['params'][0]['number'];\n } else {\n return $instance->name;\n }\n\n // nasty nesting\n if ( isset( $settings[ $num ]['title'] ) ) {\n return $settings[ $num ]['title'];\n }\n return $instance->name;\n\n}\n</code></pre>\n"
}
]
| 2017/06/19 | [
"https://wordpress.stackexchange.com/questions/270579",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121807/"
]
| Is there anyway at all to get the title of a widget from the widget id? The post title can be used by using
```
get_the_title()
```
Is there a way to get the title for a widget using the same kind or function? | You can get the widget name from the widget id with this:
```
<?php
global $wp_registered_widgets;
$id = 'recent-comments-1'; // example
if ( isset($wp_registered_widgets[$id]['name']) ) {
echo $wp_registered_widgets[$id]['name'];
}
?>
``` |
270,615 | <p>I'm trying to add multiple page IDs into an if else statement. This is my code so far: </p>
<pre><code>if ( is_page(ID) || is_page(ID) ) {
get_header('header_alt');
} else {
get_header();
}
</code></pre>
<p>I tried a few other solutions found on google, yet it always only works on the initial page after clearing the cache. </p>
| [
{
"answer_id": 270616,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": false,
"text": "<p>You can pass an array of IDs to <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"noreferrer\"><code>is_page</code></a> instead of using multiple <code>is_page</code>:</p>\n\n<pre><code>if( is_page( array( 11, 22, 33, 44 ) ) ) {\n // Your code\n}\n</code></pre>\n\n<p>Also, if you are using it in a loop, you should consider this note:</p>\n\n<blockquote>\n <p>Due to certain global variables being overwritten during The Loop,\n is_page() will not work. In order to call it after The Loop, you must\n call <code>wp_reset_query()</code> first.</p>\n</blockquote>\n"
},
{
"answer_id": 353596,
"author": "Loosie94",
"author_id": 113139,
"author_profile": "https://wordpress.stackexchange.com/users/113139",
"pm_score": 2,
"selected": false,
"text": "<p>To add to Jack Johansson's answer, this also works for page slugs.<br>\nFor example:</p>\n\n<pre><code>if( is_page( array('news', 'work', 'about', 'contact' ) ) ) {\n// Your code\n}\n</code></pre>\n"
}
]
| 2017/06/19 | [
"https://wordpress.stackexchange.com/questions/270615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121732/"
]
| I'm trying to add multiple page IDs into an if else statement. This is my code so far:
```
if ( is_page(ID) || is_page(ID) ) {
get_header('header_alt');
} else {
get_header();
}
```
I tried a few other solutions found on google, yet it always only works on the initial page after clearing the cache. | You can pass an array of IDs to [`is_page`](https://developer.wordpress.org/reference/functions/is_page/) instead of using multiple `is_page`:
```
if( is_page( array( 11, 22, 33, 44 ) ) ) {
// Your code
}
```
Also, if you are using it in a loop, you should consider this note:
>
> Due to certain global variables being overwritten during The Loop,
> is\_page() will not work. In order to call it after The Loop, you must
> call `wp_reset_query()` first.
>
>
> |
270,619 | <p>I'm trying to create a custom shortcode that uses another shortcode for a couple audio players on a Grid displaying a custom post type using Visual Composer. </p>
<p>The audio player that I would like to use is the Compact Audio Player plugin which uses a shortcode of <code>[sc_embed_player fileurl="URL OF THE MP3 FILE"]</code>. </p>
<p>What I want to do is create 2 custom shortcodes that inject the correct mp3 url into the <code>fileurl=" "</code> path when the grid loads. I'm using advanced custom fields and the code that I am using for one shortcode in my <code>functions.php</code> now is (I plan on duplicating when I can get this one to work for the other shortcode):</p>
<pre><code>function get_generic_demo() {
$demo = get_field( 'generic_demo');
echo do_shortcode('[sc_embed_player fileurl="'.$demo['url'].'"]');
}
add_shortcode( 'generic_demo', 'get_generic_demo');
</code></pre>
<p>However, it gives me an error saying I didn't input a valid url when the grid displays when my custom shortcode is entered.</p>
<p>I've tried both setting the return from ACF to file url and the array (as used above).</p>
<p>I've also tried:</p>
<pre><code>$demo = get_field( 'generic_demo', $post->ID);
</code></pre>
<p>Any help would be much appreciated</p>
| [
{
"answer_id": 270620,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>Do not use <code>echo</code> in your shortcode. Use <code>return</code> instead.</p>\n\n<pre><code>function get_generic_demo() {\n //Get the field's value\n $demo = get_field( 'generic_demo');\n //Save the URL into a variable\n $url = $demo['url'];\n // Pass it to the other shortcode and return its value\n return do_shortcode('[sc_embed_player fileurl=\"'.$url.'\"]');\n}\nadd_shortcode( 'generic_demo', 'get_generic_demo');\n</code></pre>\n\n<p>Also make sure your fields contain the proper URL format. Dump the variable by using <code>var_dump</code> to verify it. This is most likely where your problem is coming from.</p>\n"
},
{
"answer_id": 270720,
"author": "Ryan",
"author_id": 80192,
"author_profile": "https://wordpress.stackexchange.com/users/80192",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not 100% positive if this will fix it, but try pulling the global post variable into your shortcode declaration function:</p>\n\n<pre><code>function get_generic_demo() {\n global $post;\n //Get the field's value\n $demo = get_field('generic_demo');\n //Save the URL into a variable\n $url = $demo['url'];\n // Pass it to the other shortcode and return its value\n return do_shortcode('[sc_embed_player fileurl=\"'.$url.'\"]');\n}\nadd_shortcode( 'generic_demo', 'get_generic_demo');\n</code></pre>\n\n<hr>\n\n<p>** RESPONSE EDIT - 2017-06-20 @ 11:45AM **</p>\n\n<p>The issue appears to be that however Visual Composer is building the grid, the CPT IDs aren't being acknowledged. How is the rest of the data being set for each item entry (i.e. the title and description of each item)? Are you manually entering it into the grid or is it being automatically generated?</p>\n"
}
]
| 2017/06/19 | [
"https://wordpress.stackexchange.com/questions/270619",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122133/"
]
| I'm trying to create a custom shortcode that uses another shortcode for a couple audio players on a Grid displaying a custom post type using Visual Composer.
The audio player that I would like to use is the Compact Audio Player plugin which uses a shortcode of `[sc_embed_player fileurl="URL OF THE MP3 FILE"]`.
What I want to do is create 2 custom shortcodes that inject the correct mp3 url into the `fileurl=" "` path when the grid loads. I'm using advanced custom fields and the code that I am using for one shortcode in my `functions.php` now is (I plan on duplicating when I can get this one to work for the other shortcode):
```
function get_generic_demo() {
$demo = get_field( 'generic_demo');
echo do_shortcode('[sc_embed_player fileurl="'.$demo['url'].'"]');
}
add_shortcode( 'generic_demo', 'get_generic_demo');
```
However, it gives me an error saying I didn't input a valid url when the grid displays when my custom shortcode is entered.
I've tried both setting the return from ACF to file url and the array (as used above).
I've also tried:
```
$demo = get_field( 'generic_demo', $post->ID);
```
Any help would be much appreciated | Do not use `echo` in your shortcode. Use `return` instead.
```
function get_generic_demo() {
//Get the field's value
$demo = get_field( 'generic_demo');
//Save the URL into a variable
$url = $demo['url'];
// Pass it to the other shortcode and return its value
return do_shortcode('[sc_embed_player fileurl="'.$url.'"]');
}
add_shortcode( 'generic_demo', 'get_generic_demo');
```
Also make sure your fields contain the proper URL format. Dump the variable by using `var_dump` to verify it. This is most likely where your problem is coming from. |
270,640 | <p>Im not sure if my title its the correct, i need to make something in homepage to show recent custom-taxonomies used in my latest posts... like, for example:</p>
<p>I make a new post and i use a custom taxonomy called Actors: Juan</p>
<p>i want to show "Juan" taxonomy in the homepage, below a title that say "Recent actors" or something like that</p>
<p>I was thinking about a tag cloud but i dont know if i can change tags by custom taxonomy. </p>
| [
{
"answer_id": 270620,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>Do not use <code>echo</code> in your shortcode. Use <code>return</code> instead.</p>\n\n<pre><code>function get_generic_demo() {\n //Get the field's value\n $demo = get_field( 'generic_demo');\n //Save the URL into a variable\n $url = $demo['url'];\n // Pass it to the other shortcode and return its value\n return do_shortcode('[sc_embed_player fileurl=\"'.$url.'\"]');\n}\nadd_shortcode( 'generic_demo', 'get_generic_demo');\n</code></pre>\n\n<p>Also make sure your fields contain the proper URL format. Dump the variable by using <code>var_dump</code> to verify it. This is most likely where your problem is coming from.</p>\n"
},
{
"answer_id": 270720,
"author": "Ryan",
"author_id": 80192,
"author_profile": "https://wordpress.stackexchange.com/users/80192",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not 100% positive if this will fix it, but try pulling the global post variable into your shortcode declaration function:</p>\n\n<pre><code>function get_generic_demo() {\n global $post;\n //Get the field's value\n $demo = get_field('generic_demo');\n //Save the URL into a variable\n $url = $demo['url'];\n // Pass it to the other shortcode and return its value\n return do_shortcode('[sc_embed_player fileurl=\"'.$url.'\"]');\n}\nadd_shortcode( 'generic_demo', 'get_generic_demo');\n</code></pre>\n\n<hr>\n\n<p>** RESPONSE EDIT - 2017-06-20 @ 11:45AM **</p>\n\n<p>The issue appears to be that however Visual Composer is building the grid, the CPT IDs aren't being acknowledged. How is the rest of the data being set for each item entry (i.e. the title and description of each item)? Are you manually entering it into the grid or is it being automatically generated?</p>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117100/"
]
| Im not sure if my title its the correct, i need to make something in homepage to show recent custom-taxonomies used in my latest posts... like, for example:
I make a new post and i use a custom taxonomy called Actors: Juan
i want to show "Juan" taxonomy in the homepage, below a title that say "Recent actors" or something like that
I was thinking about a tag cloud but i dont know if i can change tags by custom taxonomy. | Do not use `echo` in your shortcode. Use `return` instead.
```
function get_generic_demo() {
//Get the field's value
$demo = get_field( 'generic_demo');
//Save the URL into a variable
$url = $demo['url'];
// Pass it to the other shortcode and return its value
return do_shortcode('[sc_embed_player fileurl="'.$url.'"]');
}
add_shortcode( 'generic_demo', 'get_generic_demo');
```
Also make sure your fields contain the proper URL format. Dump the variable by using `var_dump` to verify it. This is most likely where your problem is coming from. |
270,645 | <p>I am trying to write cache plugin for my web site. How can I control if post or page updated or added new page or post</p>
| [
{
"answer_id": 270650,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever a post or page is updated or created there is action hook triggered <code>save_post</code>. You can call your function when it happens:</p>\n\n<pre><code>add_action( 'save_post', function( $post_or_page_id ) {\n // Trigger your cache function or update options etc.\n}, 10, 1 );\n</code></pre>\n"
},
{
"answer_id": 270651,
"author": "Pribhav",
"author_id": 122156,
"author_profile": "https://wordpress.stackexchange.com/users/122156",
"pm_score": 1,
"selected": false,
"text": "<p>add below action in your main function file of your plugin</p>\n\n<pre><code>add_action( 'wp_insert_post', 'my_project_updated_post', 10, 3 );\n\nfunction my_project_updated_post( $post_id, $post, $update ) {\n // your code goes here\n // Every time you will get updated or newly created post id here.\n}\n</code></pre>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122055/"
]
| I am trying to write cache plugin for my web site. How can I control if post or page updated or added new page or post | add below action in your main function file of your plugin
```
add_action( 'wp_insert_post', 'my_project_updated_post', 10, 3 );
function my_project_updated_post( $post_id, $post, $update ) {
// your code goes here
// Every time you will get updated or newly created post id here.
}
``` |
270,647 | <p>I would like to call a function when a I save a setting/option in a custom admin page.</p>
| [
{
"answer_id": 270650,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever a post or page is updated or created there is action hook triggered <code>save_post</code>. You can call your function when it happens:</p>\n\n<pre><code>add_action( 'save_post', function( $post_or_page_id ) {\n // Trigger your cache function or update options etc.\n}, 10, 1 );\n</code></pre>\n"
},
{
"answer_id": 270651,
"author": "Pribhav",
"author_id": 122156,
"author_profile": "https://wordpress.stackexchange.com/users/122156",
"pm_score": 1,
"selected": false,
"text": "<p>add below action in your main function file of your plugin</p>\n\n<pre><code>add_action( 'wp_insert_post', 'my_project_updated_post', 10, 3 );\n\nfunction my_project_updated_post( $post_id, $post, $update ) {\n // your code goes here\n // Every time you will get updated or newly created post id here.\n}\n</code></pre>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122153/"
]
| I would like to call a function when a I save a setting/option in a custom admin page. | add below action in your main function file of your plugin
```
add_action( 'wp_insert_post', 'my_project_updated_post', 10, 3 );
function my_project_updated_post( $post_id, $post, $update ) {
// your code goes here
// Every time you will get updated or newly created post id here.
}
``` |
270,670 | <p>I'm trying to manually fill the Open Graph tags and I'm having some troubles in setting the content for the <code>og:image</code> tag.</p>
<p>In a single post page, I set it this way:</p>
<pre><code><?php
$thumbnailSrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
$image = esc_attr($thumbnailSrc[0]);
?>
<meta property="og:image" content="<?php echo $image ?>">
</code></pre>
<p>The result is this:</p>
<pre><code><meta property="og:image" content="/wp-content/uploads/image.jpg">
</code></pre>
<p>On the Open Graph debugger I then get this error:</p>
<pre><code>Object at URL 'http://website.com' of type 'article' is invalid because the given value '/wp-content/uploads/image.jpg' for property 'og:image:url' could not be parsed as type 'url'.
</code></pre>
<p>How can I get the attachment so that the url is: <a href="http://website.com/wp-content/uploads/image.jpg" rel="nofollow noreferrer">http://website.com/wp-content/uploads/image.jpg</a> ?</p>
| [
{
"answer_id": 270664,
"author": "Pribhav",
"author_id": 122156,
"author_profile": "https://wordpress.stackexchange.com/users/122156",
"pm_score": 4,
"selected": true,
"text": "<p>It is not possible by WooCommerce default configuration.</p>\n\n<p>You have to install below plugin.</p>\n\n<p><a href=\"https://codecanyon.net/item/woocommerce-role-based-payment-shipping-methods/18953727\" rel=\"noreferrer\">https://codecanyon.net/item/woocommerce-role-based-payment-shipping-methods/18953727</a></p>\n\n<p>or programmatically, you can refer below link.</p>\n\n<p><a href=\"https://businessbloomer.com/disable-payment-gateway-specific-user-role-woocommerce/\" rel=\"noreferrer\">https://businessbloomer.com/disable-payment-gateway-specific-user-role-woocommerce/</a></p>\n"
},
{
"answer_id": 270667,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 4,
"selected": false,
"text": "<p>You can use following:</p>\n\n<pre><code> add_filter('woocommerce_available_payment_gateways', 'filter_gateways', 1);\n function filter_gateways($gateways)\n {\n $current_user = wp_get_current_user();\n $role = $current_user->roles;\n global $woocommerce;\n /* add your user role in condition and payment method which you need to unset*/\n if ($role[0] == 'administrator') {\n unset($gateways['cod']);\n }\n return $gateways;\n }\n</code></pre>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13206/"
]
| I'm trying to manually fill the Open Graph tags and I'm having some troubles in setting the content for the `og:image` tag.
In a single post page, I set it this way:
```
<?php
$thumbnailSrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');
$image = esc_attr($thumbnailSrc[0]);
?>
<meta property="og:image" content="<?php echo $image ?>">
```
The result is this:
```
<meta property="og:image" content="/wp-content/uploads/image.jpg">
```
On the Open Graph debugger I then get this error:
```
Object at URL 'http://website.com' of type 'article' is invalid because the given value '/wp-content/uploads/image.jpg' for property 'og:image:url' could not be parsed as type 'url'.
```
How can I get the attachment so that the url is: <http://website.com/wp-content/uploads/image.jpg> ? | It is not possible by WooCommerce default configuration.
You have to install below plugin.
<https://codecanyon.net/item/woocommerce-role-based-payment-shipping-methods/18953727>
or programmatically, you can refer below link.
<https://businessbloomer.com/disable-payment-gateway-specific-user-role-woocommerce/> |
270,675 | <p>I want to convert PHP website into WordPress. So, I want to know there are a .html at end of the URL when WordPress permalink is not ended with .html. So, is it affected to SEO?</p>
| [
{
"answer_id": 270685,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 1,
"selected": false,
"text": "<p>If you currently have <code>/path/to/site.html</code> and change it to <code>/path/to/site</code>, this will affect SEO, as search engines think they know the url (the former).</p>\n\n<p>However, there are solutions to this. You can either keep the <code>.html</code> at the end of the URL (there should be no problem to use a WordPress permalink with .html in the end), or if you want to clean up your URLs, you need to redirect from one to the other (<a href=\"http://www.morevisibility.com/blogs/seo/when-and-why-to-use-301-or-302-redirects.html\" rel=\"nofollow noreferrer\">use 301 redirects</a>).</p>\n\n<p>There is extensive material on how redirects work (<a href=\"https://stackoverflow.com/questions/20563772/reference-mod-rewrite-url-rewriting-and-pretty-links-explained\">like this</a>), if you only want the .html to disappear (and rest of the URL stays the same), something like this could already work in an .htaccess</p>\n\n<pre><code>RewriteRule ^(*.)\\.html$ $1 [R=301,QSA,L]\n</code></pre>\n\n<p>Otherwise, you'd need a more complex structure which depends on your specific current situation.</p>\n"
},
{
"answer_id": 362925,
"author": "Gulf State Software",
"author_id": 100670,
"author_profile": "https://wordpress.stackexchange.com/users/100670",
"pm_score": 0,
"selected": false,
"text": "<p>There is a plugin name '.html on PAGE', which will convert all pages to <code>.html</code> page. If you use this plugin you might also need to change in permalink to <code>/%postname%.html</code></p>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114646/"
]
| I want to convert PHP website into WordPress. So, I want to know there are a .html at end of the URL when WordPress permalink is not ended with .html. So, is it affected to SEO? | If you currently have `/path/to/site.html` and change it to `/path/to/site`, this will affect SEO, as search engines think they know the url (the former).
However, there are solutions to this. You can either keep the `.html` at the end of the URL (there should be no problem to use a WordPress permalink with .html in the end), or if you want to clean up your URLs, you need to redirect from one to the other ([use 301 redirects](http://www.morevisibility.com/blogs/seo/when-and-why-to-use-301-or-302-redirects.html)).
There is extensive material on how redirects work ([like this](https://stackoverflow.com/questions/20563772/reference-mod-rewrite-url-rewriting-and-pretty-links-explained)), if you only want the .html to disappear (and rest of the URL stays the same), something like this could already work in an .htaccess
```
RewriteRule ^(*.)\.html$ $1 [R=301,QSA,L]
```
Otherwise, you'd need a more complex structure which depends on your specific current situation. |
270,737 | <p>After the update to <strong>Wordpress 4.8</strong> my widget's textarea has disappeared and my console says: </p>
<pre><code>[Error] ReferenceError: Can't find variable: wp
Global Code (widgets.php:202)
</code></pre>
<p>Looking at the file I can identify this line causing the issue:</p>
<pre><code>wp.textWidgets.init();
</code></pre>
<p>Now, I've got installed many plugins but even deactivating all those I can't solve it. Any suggestion?</p>
| [
{
"answer_id": 270740,
"author": "Andrew Dinmore",
"author_id": 115658,
"author_profile": "https://wordpress.stackexchange.com/users/115658",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like you need to enqueue the editor scripts manually, after 4.8, using <code>wp_enqueue_editor()</code> in your theme/plugin: <a href=\"https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/</a></p>\n"
},
{
"answer_id": 270881,
"author": "middlelady",
"author_id": 93927,
"author_profile": "https://wordpress.stackexchange.com/users/93927",
"pm_score": -1,
"selected": false,
"text": "<p>I actually had to restore manually the Wordpress core and to deactivate a function in my theme which deferred all the javascript.</p>\n"
}
]
| 2017/06/20 | [
"https://wordpress.stackexchange.com/questions/270737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93927/"
]
| After the update to **Wordpress 4.8** my widget's textarea has disappeared and my console says:
```
[Error] ReferenceError: Can't find variable: wp
Global Code (widgets.php:202)
```
Looking at the file I can identify this line causing the issue:
```
wp.textWidgets.init();
```
Now, I've got installed many plugins but even deactivating all those I can't solve it. Any suggestion? | Looks like you need to enqueue the editor scripts manually, after 4.8, using `wp_enqueue_editor()` in your theme/plugin: <https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/> |
270,777 | <p>I'm having trouble with my WordPress theme.</p>
<p>I'm getting the error below after uploading a featured image into my portfolio item(s):</p>
<blockquote>
<p>Warning: Invalid argument supplied for foreach() in /home2/maryhtran/public_html/wp-content/themes/Motive/portfolio-list.php on line 150</p>
</blockquote>
<p>This is the code that is causing the error found in <code>portfolio-list.php</code>:</p>
<pre><code>// Get the terms( categories ) for the portfolio item
$terms = get_the_terms( $post_item->ID, 'portfolio_categories' );
foreach( $terms as $term ) {
// some code here
}
</code></pre>
<p>Could someone please help me understand why this is happening and how I can fix this error?</p>
| [
{
"answer_id": 270780,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>The error is in your theme. Contact the theme support people. That is the proper place to ask theme-related questions.</p>\n\n<p>(But, the error looks like the <code>get_the_terms()</code> function is not returning an array, so the <code>foreach</code> won't work.)</p>\n\n<p>That has to be fixed by the theme author.</p>\n"
},
{
"answer_id": 270805,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>It happens when the <code>foreach()</code> is fed with an invalid entry, because there is no term returned. To prevent this, wrap your loop inside a conditional:</p>\n\n<pre><code>// Get the terms( categories ) for the portfolio item\n$terms = get_the_terms( $post_item->ID, 'portfolio_categories' );\nif(is_array($terms) || is_object($terms)){\n foreach( $terms as $term ) {\n // some code here\n }\n}\n</code></pre>\n\n<p>Now, the loop will only run only the post has some terms.</p>\n"
},
{
"answer_id": 270811,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<p>It will be a little hard to predict but here are some options you could try:</p>\n\n<ol>\n<li>Try echoing out the post id to see it it is actually populating.</li>\n<li>Check if \"portfolio_categories\" is the exact name to your taxonomy. You can hover over the link in admin panel and look for \"taxonomy=[some_name]\" in the URL.</li>\n</ol>\n\n<p>Check these things and see what you can find.</p>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122237/"
]
| I'm having trouble with my WordPress theme.
I'm getting the error below after uploading a featured image into my portfolio item(s):
>
> Warning: Invalid argument supplied for foreach() in /home2/maryhtran/public\_html/wp-content/themes/Motive/portfolio-list.php on line 150
>
>
>
This is the code that is causing the error found in `portfolio-list.php`:
```
// Get the terms( categories ) for the portfolio item
$terms = get_the_terms( $post_item->ID, 'portfolio_categories' );
foreach( $terms as $term ) {
// some code here
}
```
Could someone please help me understand why this is happening and how I can fix this error? | It happens when the `foreach()` is fed with an invalid entry, because there is no term returned. To prevent this, wrap your loop inside a conditional:
```
// Get the terms( categories ) for the portfolio item
$terms = get_the_terms( $post_item->ID, 'portfolio_categories' );
if(is_array($terms) || is_object($terms)){
foreach( $terms as $term ) {
// some code here
}
}
```
Now, the loop will only run only the post has some terms. |
270,783 | <p>I am trying to implement a simple login inside my plugin following <a href="http://www.w3schools.in/php-script/php-login-without-using-database/" rel="nofollow noreferrer">this tutorial</a>. I have successfully implemented the login inside a WP admin page, but I can't seem to redirect it to <code>index.php</code>. Also, <code>index.php</code> must still be contained inside an admin page. Here's a portion of my code:</p>
<pre><code>session_start();
add_action('admin_menu', 'sample_setup_menu');
function sample_setup_menu(){
add_menu_page('sample Foo', 'sample Foo', 'manage_options', 'sample-plugin', 'login_init');
}
function login_init(){
/* Check Login form submitted */
//$_POST['Submit']
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('Alex' => '123456','username1' => 'password1','username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
//$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Username = isset($_GET['page']) ? $_GET['page'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
$_SESSION['UserData']['Username']=$logins[$Username];
header("location: index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
require_once('login.php');
}
</code></pre>
| [
{
"answer_id": 271074,
"author": "Pravin Work",
"author_id": 120969,
"author_profile": "https://wordpress.stackexchange.com/users/120969",
"pm_score": 0,
"selected": false,
"text": "<p>try adding submenu pages</p>\n\n<pre><code>add_submenu_page( 'sample-plugin', 'Sample Page', 'title', 'administrator', 'slug-fo-page', 'slug-for-page' );\n</code></pre>\n"
},
{
"answer_id": 301806,
"author": "Prashant Walke",
"author_id": 142260,
"author_profile": "https://wordpress.stackexchange.com/users/142260",
"pm_score": 2,
"selected": false,
"text": "<p>Using add_submenu_page function WordPress you can add multiple pages/menu</p>\n\n<p>In order to add a new top-level menu to WordPress administration dashboard, You can use <code>add_menu_page()</code> function. This function has the following syntax.</p>\n\n<pre><code>//add plugin menu\n\n add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);\n</code></pre>\n\n<p>As you can see, The function accepts the following parameters.</p>\n\n<p><strong>page_title:</strong> The page title.</p>\n\n<p><strong>menu_title:</strong> The menu title displayed on the dashboard.</p>\n\n<p><strong>capability:</strong> the Minimum capability to view the menu.</p>\n\n<p><strong>menu_slug:</strong> Unique name used as a slug for the menu item.</p>\n\n<p><strong>function:</strong> A callback function used to display page content.</p>\n\n<p><strong>icon_url:</strong> URL to a custom image used as the icon.</p>\n\n<p><strong>position:</strong> Location in the menu order.</p>\n\n<p><strong>Adding a Submenu</strong></p>\n\n<p>There are two types of submenus, menu items listed below your top-level menu and menu item listed below existing default menus in WordPress. To add submenus under your top-level menu, You can use add_submenu_page() function. This function has the following syntax.</p>\n\n<pre><code>//add submenu\nadd_submenu_page($parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function);\n</code></pre>\n\n<p>As you can see, this function accepts the following parameters.</p>\n\n<p><strong>parent_slug:</strong> Slug of the parent menu item.</p>\n\n<p><strong>page_title:</strong> The page title.</p>\n\n<p><strong>menu_title:</strong> The submenu title displayed on the dashboard.</p>\n\n<p><strong>capability:</strong> the Minimum capability to view the submenu.</p>\n\n<p><strong>menu_slug:</strong> Unique name used as a slug for submenu item.</p>\n\n<p><strong>function:</strong> A callback function used to display page content.</p>\n\n<p>Ex:</p>\n\n<pre><code>add_action('admin_menu', 'my_menu_pages');\nfunction my_menu_pages(){\n add_menu_page('My Page Title', 'My Menu Title', 'manage_options', 'my-menu', 'my_menu_output' );\n add_submenu_page('my-menu', 'Submenu Page Title', 'Whatever You Want', 'manage_options', 'my-menu' );\n add_submenu_page('my-menu', 'Submenu Page Title2', 'Whatever You Want2', 'manage_options', 'my-menu2' );\n}\n</code></pre>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270783",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121819/"
]
| I am trying to implement a simple login inside my plugin following [this tutorial](http://www.w3schools.in/php-script/php-login-without-using-database/). I have successfully implemented the login inside a WP admin page, but I can't seem to redirect it to `index.php`. Also, `index.php` must still be contained inside an admin page. Here's a portion of my code:
```
session_start();
add_action('admin_menu', 'sample_setup_menu');
function sample_setup_menu(){
add_menu_page('sample Foo', 'sample Foo', 'manage_options', 'sample-plugin', 'login_init');
}
function login_init(){
/* Check Login form submitted */
//$_POST['Submit']
if(isset($_POST['Submit'])){
/* Define username and associated password array */
$logins = array('Alex' => '123456','username1' => 'password1','username2' => 'password2');
/* Check and assign submitted Username and Password to new variable */
//$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Username = isset($_GET['page']) ? $_GET['page'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
$_SESSION['UserData']['Username']=$logins[$Username];
header("location: index.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>Invalid Login Details</span>";
}
}
require_once('login.php');
}
``` | Using add\_submenu\_page function WordPress you can add multiple pages/menu
In order to add a new top-level menu to WordPress administration dashboard, You can use `add_menu_page()` function. This function has the following syntax.
```
//add plugin menu
add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
```
As you can see, The function accepts the following parameters.
**page\_title:** The page title.
**menu\_title:** The menu title displayed on the dashboard.
**capability:** the Minimum capability to view the menu.
**menu\_slug:** Unique name used as a slug for the menu item.
**function:** A callback function used to display page content.
**icon\_url:** URL to a custom image used as the icon.
**position:** Location in the menu order.
**Adding a Submenu**
There are two types of submenus, menu items listed below your top-level menu and menu item listed below existing default menus in WordPress. To add submenus under your top-level menu, You can use add\_submenu\_page() function. This function has the following syntax.
```
//add submenu
add_submenu_page($parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function);
```
As you can see, this function accepts the following parameters.
**parent\_slug:** Slug of the parent menu item.
**page\_title:** The page title.
**menu\_title:** The submenu title displayed on the dashboard.
**capability:** the Minimum capability to view the submenu.
**menu\_slug:** Unique name used as a slug for submenu item.
**function:** A callback function used to display page content.
Ex:
```
add_action('admin_menu', 'my_menu_pages');
function my_menu_pages(){
add_menu_page('My Page Title', 'My Menu Title', 'manage_options', 'my-menu', 'my_menu_output' );
add_submenu_page('my-menu', 'Submenu Page Title', 'Whatever You Want', 'manage_options', 'my-menu' );
add_submenu_page('my-menu', 'Submenu Page Title2', 'Whatever You Want2', 'manage_options', 'my-menu2' );
}
``` |
270,784 | <p>I tried this code to create some meta boxes is all working fine, the problem I am facing is how to sanitize the text fields and update post meta </p>
<pre><code> function Print_price_fileds($cnt, $p = null) {
if ($p === null){
$a = $b = $c = '';
}else{
$a = $p['n'];
$b = $p['d'];
$c = $p['p'];
}
return <<<HTML
<li>
<label>Nr :</label>
<input type="text" name="price_data[$cnt][n]" size="10" value="$a"/>
<label>Description :</label>
<input type="text" name="price_data[$cnt][d]" size="50" value="$b"/>
<label>Price :</label>
<input type="text" name="price_data[$cnt][p]" size="20" value="$c"/>
<span class="remove">Remove</span>
</li>
HTML
;
}
//add custom field - price
add_action("add_meta_boxes", "object_init");
function object_init(){
add_meta_box("price_meta_id", "Price fields :","price_meta", "post",
"normal", "low");
}
function price_meta(){
global $post;
$data = get_post_meta($post->ID,"price_data",true);
echo '<div>';
echo '<ul id="price_items">';
$c = 0;
if (count($data) > 0){
foreach((array)$data as $p ){
if (isset($p['p']) || isset($p['d'])|| isset($p['n'])){
echo Print_price_fileds($c,$p);
$c = $c +1;
}
}
}
echo '</ul>';
?>
<span id="here"></span>
<span class="add"><?php echo __('Add Price Data'); ?></span>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c - 1; ?>; // substract 1 from $c
$(".add").click(function() {
count = count + 1;
//$('#price_items').append('<li><label>Nr :</label><input type="text" name="price_data[' + count + '][n]" size="10" value=""/><label>Description :</label><input type="text" name="price_data[' + count + '][d]" size="50" value=""/><label>Price :</label><input type="text" name="price_data[' + count + '][p]" size="20" value=""/><span class="remove">Remove</span></li>');
$('#price_items').append('<? echo implode('',explode("\n",Print_price_fileds('count'))); ?>'.replace(/count/g, count));
return false;
});
$(".remove").live('click', function() {
$(this).parent().remove();
});
});
</script>
<style>#price_items {list-style: none;}</style>
<?php
echo '</div>';
}
//Save product price
add_action('save_post', 'save_detailss');
function save_detailss($post_id){
global $post;
// to prevent metadata or custom fields from disappearing...
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// OK, we're authenticated: we need to find and save the data
if (isset($_POST['price_data'])){
$data = $_POST['price_data'];
update_post_meta($post_id,'price_data',$data);
}else{
delete_post_meta($post_id,'price_data');
}
}
</code></pre>
| [
{
"answer_id": 270794,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress use <code>add_magic_quotes()</code> to escape incoming data from <code>$_POST</code>, <code>$_GET</code> and <code>$_COOKIE</code>and <code>$_SERVER</code>in load.php on line 647. You can use structur of this function to build Your own function which can sanitize every element in array:</p>\n\n<pre><code>function add_magic_quotes( $array ) {\n foreach ( (array) $array as $k => $v ) {\n if ( is_array( $v ) ) {\n $array[$k] = add_magic_quotes( $v );\n } else {\n $array[$k] = addslashes( $v );\n }\n}\nreturn $array;\n</code></pre>\n\n<p>}</p>\n\n<p>in place of addslashes You can use your needed function. \nExample: </p>\n\n<pre><code>function sanitize_price_array( $array ) {\n foreach ( (array) $array as $k => $v ) {\n if ( is_array( $v ) ) {\n $array[$k] = sanitize_price_array( $v );\n } else {\n $array[$k] = sanitize_text_field( $v );\n }\n }\n\n return $array; \n}\n\n$data = sanitize_price_array( $_POST['price_data']);\n</code></pre>\n"
},
{
"answer_id": 270795,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>The best way to sanitize text fields within WordPress is to use <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\"><code>sanitize_text_field()</code></a> function:</p>\n\n<pre><code>$data = sanitize_text_field( $_POST['key'] );\n</code></pre>\n\n<p>Additionally, if you register the meta field properly width <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> function, you can define the sanitize callback and the expected data type as well. For example:</p>\n\n<pre><code>add_action( 'init', 'cyb_register_meta_fields' );\nfunction cyb_register_meta_fields() {\n $args = array(\n 'sanitize_callback' => 'sanitize_text_field'\n );\n register_meta( 'post', 'key', $args );\n}\n</code></pre>\n\n<p>By using <code>register_meta()</code> you don't need to sanitize the meta field every time you upadate or create it, just use <code>upadate_post_meta()</code>/<code>add_post_meta()</code> and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:</p>\n\n<pre><code>add_action( 'init', 'cyb_register_meta_fields' );\nfunction cyb_register_meta_fields() {\n\n $args = array(\n 'sanitize_callback' => 'sanitize_price_field'\n );\n\n register_meta( 'post', 'price_data', $args );\n\n}\n\nfunction sanitize_price_field( $meta_value ) {\n\n foreach ( (array) $meta_value as $k => $v ) {\n if ( is_array( $v ) ) {\n $meta_value[$k] = sanitize_price_field( $v );\n } else {\n $meta_value[$k] = sanitize_text_field( $v );\n }\n }\n\n return $meta_value;\n\n}\n</code></pre>\n"
},
{
"answer_id": 408647,
"author": "Ziaur Rahman",
"author_id": 224969,
"author_profile": "https://wordpress.stackexchange.com/users/224969",
"pm_score": 0,
"selected": false,
"text": "<p>you can use <code>map_deep()</code> to sanitize the array text field.</p>\n<pre><code>map_deep( wp_unslash( $_POST['price_data'] ) , 'sanitize_text_field' );\n</code></pre>\n<p>It may solve the issue.</p>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270784",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122240/"
]
| I tried this code to create some meta boxes is all working fine, the problem I am facing is how to sanitize the text fields and update post meta
```
function Print_price_fileds($cnt, $p = null) {
if ($p === null){
$a = $b = $c = '';
}else{
$a = $p['n'];
$b = $p['d'];
$c = $p['p'];
}
return <<<HTML
<li>
<label>Nr :</label>
<input type="text" name="price_data[$cnt][n]" size="10" value="$a"/>
<label>Description :</label>
<input type="text" name="price_data[$cnt][d]" size="50" value="$b"/>
<label>Price :</label>
<input type="text" name="price_data[$cnt][p]" size="20" value="$c"/>
<span class="remove">Remove</span>
</li>
HTML
;
}
//add custom field - price
add_action("add_meta_boxes", "object_init");
function object_init(){
add_meta_box("price_meta_id", "Price fields :","price_meta", "post",
"normal", "low");
}
function price_meta(){
global $post;
$data = get_post_meta($post->ID,"price_data",true);
echo '<div>';
echo '<ul id="price_items">';
$c = 0;
if (count($data) > 0){
foreach((array)$data as $p ){
if (isset($p['p']) || isset($p['d'])|| isset($p['n'])){
echo Print_price_fileds($c,$p);
$c = $c +1;
}
}
}
echo '</ul>';
?>
<span id="here"></span>
<span class="add"><?php echo __('Add Price Data'); ?></span>
<script>
var $ =jQuery.noConflict();
$(document).ready(function() {
var count = <?php echo $c - 1; ?>; // substract 1 from $c
$(".add").click(function() {
count = count + 1;
//$('#price_items').append('<li><label>Nr :</label><input type="text" name="price_data[' + count + '][n]" size="10" value=""/><label>Description :</label><input type="text" name="price_data[' + count + '][d]" size="50" value=""/><label>Price :</label><input type="text" name="price_data[' + count + '][p]" size="20" value=""/><span class="remove">Remove</span></li>');
$('#price_items').append('<? echo implode('',explode("\n",Print_price_fileds('count'))); ?>'.replace(/count/g, count));
return false;
});
$(".remove").live('click', function() {
$(this).parent().remove();
});
});
</script>
<style>#price_items {list-style: none;}</style>
<?php
echo '</div>';
}
//Save product price
add_action('save_post', 'save_detailss');
function save_detailss($post_id){
global $post;
// to prevent metadata or custom fields from disappearing...
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// OK, we're authenticated: we need to find and save the data
if (isset($_POST['price_data'])){
$data = $_POST['price_data'];
update_post_meta($post_id,'price_data',$data);
}else{
delete_post_meta($post_id,'price_data');
}
}
``` | The best way to sanitize text fields within WordPress is to use [`sanitize_text_field()`](https://developer.wordpress.org/reference/functions/sanitize_text_field/) function:
```
$data = sanitize_text_field( $_POST['key'] );
```
Additionally, if you register the meta field properly width [`register_meta()`](https://developer.wordpress.org/reference/functions/register_meta/) function, you can define the sanitize callback and the expected data type as well. For example:
```
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_text_field'
);
register_meta( 'post', 'key', $args );
}
```
By using `register_meta()` you don't need to sanitize the meta field every time you upadate or create it, just use `upadate_post_meta()`/`add_post_meta()` and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:
```
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_price_field'
);
register_meta( 'post', 'price_data', $args );
}
function sanitize_price_field( $meta_value ) {
foreach ( (array) $meta_value as $k => $v ) {
if ( is_array( $v ) ) {
$meta_value[$k] = sanitize_price_field( $v );
} else {
$meta_value[$k] = sanitize_text_field( $v );
}
}
return $meta_value;
}
``` |
270,797 | <p>I have multi site. (3 websites)
So I want to apply different theme in one of the website. But when I activate the theme. All the sites are affected. Is it how the multisite works?? Can somebody clarify what can be done with multi site?</p>
<ol>
<li>Install MultiSite (Sub-Directory)</li>
<li><p>Modified wp-config.php and .htaccess</p>
<pre><code>define( 'WP_ALLOW_MULTISITE', true );
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'localhost:8020');
define('PATH_CURRENT_SITE', '/multi/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
</code></pre></li>
</ol>
<p>and .htaccess</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /multi/
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
</code></pre>
<ol start="3">
<li>Create another 2 sites</li>
</ol>
<p><a href="https://i.stack.imgur.com/FOGXv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FOGXv.png" alt="enter image description here"></a></p>
<p>For some reason (The colon in the URL : before the port number is missing(another issue?)) so I modify the setting of the site to add colon because there's an error when I visit site.
<a href="https://i.stack.imgur.com/w9i2D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w9i2D.png" alt="enter image description here"></a></p>
<ol start="4">
<li>Network activated the themes</li>
<li>Activate theme1 in site1</li>
<li>Activate theme2 in site2</li>
</ol>
<p>But all the sites are the same.</p>
<p>I noticed that before I activate the theme the URL is</p>
<pre><code>http://localhost:8020/multi/site2/wp-admin/themes.php
</code></pre>
<p>after I activated, it redirects to: </p>
<pre><code>http://localhost:8020/multi/wp-admin/themes.php
</code></pre>
<p>Where did I go wrong? </p>
| [
{
"answer_id": 270794,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 2,
"selected": false,
"text": "<p>Wordpress use <code>add_magic_quotes()</code> to escape incoming data from <code>$_POST</code>, <code>$_GET</code> and <code>$_COOKIE</code>and <code>$_SERVER</code>in load.php on line 647. You can use structur of this function to build Your own function which can sanitize every element in array:</p>\n\n<pre><code>function add_magic_quotes( $array ) {\n foreach ( (array) $array as $k => $v ) {\n if ( is_array( $v ) ) {\n $array[$k] = add_magic_quotes( $v );\n } else {\n $array[$k] = addslashes( $v );\n }\n}\nreturn $array;\n</code></pre>\n\n<p>}</p>\n\n<p>in place of addslashes You can use your needed function. \nExample: </p>\n\n<pre><code>function sanitize_price_array( $array ) {\n foreach ( (array) $array as $k => $v ) {\n if ( is_array( $v ) ) {\n $array[$k] = sanitize_price_array( $v );\n } else {\n $array[$k] = sanitize_text_field( $v );\n }\n }\n\n return $array; \n}\n\n$data = sanitize_price_array( $_POST['price_data']);\n</code></pre>\n"
},
{
"answer_id": 270795,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": true,
"text": "<p>The best way to sanitize text fields within WordPress is to use <a href=\"https://developer.wordpress.org/reference/functions/sanitize_text_field/\" rel=\"nofollow noreferrer\"><code>sanitize_text_field()</code></a> function:</p>\n\n<pre><code>$data = sanitize_text_field( $_POST['key'] );\n</code></pre>\n\n<p>Additionally, if you register the meta field properly width <a href=\"https://developer.wordpress.org/reference/functions/register_meta/\" rel=\"nofollow noreferrer\"><code>register_meta()</code></a> function, you can define the sanitize callback and the expected data type as well. For example:</p>\n\n<pre><code>add_action( 'init', 'cyb_register_meta_fields' );\nfunction cyb_register_meta_fields() {\n $args = array(\n 'sanitize_callback' => 'sanitize_text_field'\n );\n register_meta( 'post', 'key', $args );\n}\n</code></pre>\n\n<p>By using <code>register_meta()</code> you don't need to sanitize the meta field every time you upadate or create it, just use <code>upadate_post_meta()</code>/<code>add_post_meta()</code> and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:</p>\n\n<pre><code>add_action( 'init', 'cyb_register_meta_fields' );\nfunction cyb_register_meta_fields() {\n\n $args = array(\n 'sanitize_callback' => 'sanitize_price_field'\n );\n\n register_meta( 'post', 'price_data', $args );\n\n}\n\nfunction sanitize_price_field( $meta_value ) {\n\n foreach ( (array) $meta_value as $k => $v ) {\n if ( is_array( $v ) ) {\n $meta_value[$k] = sanitize_price_field( $v );\n } else {\n $meta_value[$k] = sanitize_text_field( $v );\n }\n }\n\n return $meta_value;\n\n}\n</code></pre>\n"
},
{
"answer_id": 408647,
"author": "Ziaur Rahman",
"author_id": 224969,
"author_profile": "https://wordpress.stackexchange.com/users/224969",
"pm_score": 0,
"selected": false,
"text": "<p>you can use <code>map_deep()</code> to sanitize the array text field.</p>\n<pre><code>map_deep( wp_unslash( $_POST['price_data'] ) , 'sanitize_text_field' );\n</code></pre>\n<p>It may solve the issue.</p>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270797",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113284/"
]
| I have multi site. (3 websites)
So I want to apply different theme in one of the website. But when I activate the theme. All the sites are affected. Is it how the multisite works?? Can somebody clarify what can be done with multi site?
1. Install MultiSite (Sub-Directory)
2. Modified wp-config.php and .htaccess
```
define( 'WP_ALLOW_MULTISITE', true );
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'localhost:8020');
define('PATH_CURRENT_SITE', '/multi/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
and .htaccess
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /multi/
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
```
3. Create another 2 sites
[](https://i.stack.imgur.com/FOGXv.png)
For some reason (The colon in the URL : before the port number is missing(another issue?)) so I modify the setting of the site to add colon because there's an error when I visit site.
[](https://i.stack.imgur.com/w9i2D.png)
4. Network activated the themes
5. Activate theme1 in site1
6. Activate theme2 in site2
But all the sites are the same.
I noticed that before I activate the theme the URL is
```
http://localhost:8020/multi/site2/wp-admin/themes.php
```
after I activated, it redirects to:
```
http://localhost:8020/multi/wp-admin/themes.php
```
Where did I go wrong? | The best way to sanitize text fields within WordPress is to use [`sanitize_text_field()`](https://developer.wordpress.org/reference/functions/sanitize_text_field/) function:
```
$data = sanitize_text_field( $_POST['key'] );
```
Additionally, if you register the meta field properly width [`register_meta()`](https://developer.wordpress.org/reference/functions/register_meta/) function, you can define the sanitize callback and the expected data type as well. For example:
```
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_text_field'
);
register_meta( 'post', 'key', $args );
}
```
By using `register_meta()` you don't need to sanitize the meta field every time you upadate or create it, just use `upadate_post_meta()`/`add_post_meta()` and the sanitize callback will be used automatically. So, if your meta field is an array, it could be something like this:
```
add_action( 'init', 'cyb_register_meta_fields' );
function cyb_register_meta_fields() {
$args = array(
'sanitize_callback' => 'sanitize_price_field'
);
register_meta( 'post', 'price_data', $args );
}
function sanitize_price_field( $meta_value ) {
foreach ( (array) $meta_value as $k => $v ) {
if ( is_array( $v ) ) {
$meta_value[$k] = sanitize_price_field( $v );
} else {
$meta_value[$k] = sanitize_text_field( $v );
}
}
return $meta_value;
}
``` |
270,834 | <p>I have registered scripts which are supposed to load in head section. But for some reason I don't get these links loaded in head. Instead of loading scripts in head these are loading in footer.</p>
<pre><code> add_action('init', 'my_enqueued_assets');
function my_enqueued_assets() {
//Register Css
wp_register_style('my-css', MY_PLUGIN_URL.'css/my_styles.css');
wp_register_style('my-admin-css', MY_PLUGIN_URL.'css/my_admin_styles.css');
//Register JS
wp_register_script('my-jquery-min', MY_PLUGIN_URL.'js/jquery-3.2.1.min.js');
wp_register_script('my-script-min', MY_PLUGIN_URL.'js/my_isotope.min.js');
wp_register_script('my-script', MY_PLUGIN_URL.'js/my_isotope.js', array('jquery'), my_PLUGIN_VERSION, false );
wp_register_script('my-lightbox-script', MY_PLUGIN_URL.'js/my-lightbox.js', array('jquery'), my_PLUGIN_VERSION, false );
wp_register_script('my-prefix-script',MY_PLUGIN_URL.'/js/myscript.js', array('jquery'), '0.1',false );
}
</code></pre>
<p>I loaded these scripts in shortcode to load scripts and style when only shortcode is used or called.</p>
<pre><code>function my_shortcodes_init()
{
function my_shortcode($atts = [], $content = null)
{
//default portfolio value
$id = 1;
wp_enqueue_style('my-css');
wp_enqueue_script('my-jquery-min');
wp_enqueue_script('my-script-min');
wp_enqueue_script('my-script');
wp_enqueue_script('my-lightbox-script');
if (isset($atts["id"])) {
$id = $atts["id"];
}
require MY_PLUGIN_DIR.'views/isotope.php';
}
add_shortcode('MY_GALLERY', 'my_shortcode');
}
add_action('init', 'my_shortcodes_init');
</code></pre>
| [
{
"answer_id": 270835,
"author": "joetek",
"author_id": 62298,
"author_profile": "https://wordpress.stackexchange.com/users/62298",
"pm_score": 0,
"selected": false,
"text": "<p>The final argument in the <code>wp-enqueue-script</code> <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">function</a> is a boolean which specifies whether the script should appear in the footer.</p>\n\n<pre><code>wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );\n</code></pre>\n\n<p>The first two scripts in your example do not specify the optional arguments, so it will default to <code>true</code>, putting the scripts down in the footer.</p>\n"
},
{
"answer_id": 271075,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>This happens because of the order of execution of your WordPress page. In your code it goes like this:</p>\n\n<ol>\n<li>At <code>init</code>, which is early in the generation process of the page, you are registering the scripts. That is, you are telling WP that you want to use these later on. No html is generated.</li>\n<li>At <code>init</code> you are also registering a shortcode. This means that you are defining a function that will be triggered once the shortcode has been encountered. No html is generated.</li>\n<li>WP then goes on generating the html. First the head of the page, menus and so on, until it comes to the post content.</li>\n<li>In the post content it finds the shortcode and starts executing the function <code>my_shortcode</code> you have defined. Inside this function it finds <code>wp_enqueue_script</code>. At this point the html of the head already has been generated. So it has no choice but placing the html with the scripts in the footer of the page.</li>\n</ol>\n\n<p>If you want the scripts in the head, you must make sure <code>wp_enqueue_scripts</code> is triggered at <code>init</code>. Of course, this means they will also be enqueued when there is no shortcode in the content.</p>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120969/"
]
| I have registered scripts which are supposed to load in head section. But for some reason I don't get these links loaded in head. Instead of loading scripts in head these are loading in footer.
```
add_action('init', 'my_enqueued_assets');
function my_enqueued_assets() {
//Register Css
wp_register_style('my-css', MY_PLUGIN_URL.'css/my_styles.css');
wp_register_style('my-admin-css', MY_PLUGIN_URL.'css/my_admin_styles.css');
//Register JS
wp_register_script('my-jquery-min', MY_PLUGIN_URL.'js/jquery-3.2.1.min.js');
wp_register_script('my-script-min', MY_PLUGIN_URL.'js/my_isotope.min.js');
wp_register_script('my-script', MY_PLUGIN_URL.'js/my_isotope.js', array('jquery'), my_PLUGIN_VERSION, false );
wp_register_script('my-lightbox-script', MY_PLUGIN_URL.'js/my-lightbox.js', array('jquery'), my_PLUGIN_VERSION, false );
wp_register_script('my-prefix-script',MY_PLUGIN_URL.'/js/myscript.js', array('jquery'), '0.1',false );
}
```
I loaded these scripts in shortcode to load scripts and style when only shortcode is used or called.
```
function my_shortcodes_init()
{
function my_shortcode($atts = [], $content = null)
{
//default portfolio value
$id = 1;
wp_enqueue_style('my-css');
wp_enqueue_script('my-jquery-min');
wp_enqueue_script('my-script-min');
wp_enqueue_script('my-script');
wp_enqueue_script('my-lightbox-script');
if (isset($atts["id"])) {
$id = $atts["id"];
}
require MY_PLUGIN_DIR.'views/isotope.php';
}
add_shortcode('MY_GALLERY', 'my_shortcode');
}
add_action('init', 'my_shortcodes_init');
``` | This happens because of the order of execution of your WordPress page. In your code it goes like this:
1. At `init`, which is early in the generation process of the page, you are registering the scripts. That is, you are telling WP that you want to use these later on. No html is generated.
2. At `init` you are also registering a shortcode. This means that you are defining a function that will be triggered once the shortcode has been encountered. No html is generated.
3. WP then goes on generating the html. First the head of the page, menus and so on, until it comes to the post content.
4. In the post content it finds the shortcode and starts executing the function `my_shortcode` you have defined. Inside this function it finds `wp_enqueue_script`. At this point the html of the head already has been generated. So it has no choice but placing the html with the scripts in the footer of the page.
If you want the scripts in the head, you must make sure `wp_enqueue_scripts` is triggered at `init`. Of course, this means they will also be enqueued when there is no shortcode in the content. |
270,855 | <p>I'm editing the category.php template and I need an array of current category child's.</p>
<p>I'm able to get an array with current category child's but there are too many keys, I'm using the following:</p>
<pre><code>//get category ID
$catego = get_category( get_query_var( 'cat' ) );
$cat_id = $catego->cat_ID;
//list current category childs
$catlist = get_categories(
array(
'child_of' => $cat_id,
'orderby' => 'id',
'order' => 'ASC'
) );
</code></pre>
<p>That gives me the following:</p>
<pre><code>Array
(
[0] => WP_Term Object
(
[term_id] => 11
[name] => test1
[slug] => test1
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 3
[filter] => raw
[cat_ID] => 11
[category_count] => 3
[category_description] =>
[cat_name] => test1
[category_nicename] => test1
[category_parent] => 10
)
[1] => WP_Term Object
(
[term_id] => 12
[name] => test2
[slug] => test2
[term_group] => 0
[term_taxonomy_id] => 12
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 1
[filter] => raw
[cat_ID] => 12
[category_count] => 1
[category_description] =>
[cat_name] => test2
[category_nicename] => test2
[category_parent] => 10
)
)
</code></pre>
<p>Now from this array I want to create an array which will only have the [cat_ID] key. I've tried the following but it gives me nothing ( <a href="http://php.net/manual/en/function.array-column.php" rel="nofollow noreferrer">http://php.net/manual/en/function.array-column.php</a> ):</p>
<pre><code>$category_id = array_column($catlist, '[cat_ID]');
print_r($category_id);
</code></pre>
<p>Any ideas? Thanks in advance.</p>
| [
{
"answer_id": 270856,
"author": "Senta",
"author_id": 122290,
"author_profile": "https://wordpress.stackexchange.com/users/122290",
"pm_score": 0,
"selected": false,
"text": "<p>A foreach loop works:</p>\n\n<pre><code>$category_id = array();\nforeach ($catlist as $cat){\n $category_id[] = $cat->cat_ID;\n}\n</code></pre>\n"
},
{
"answer_id": 270857,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 2,
"selected": true,
"text": "<p>Try this :</p>\n\n<pre><code>// This converts the WP_Term Object to array.\n$catlist = json_decode(json_encode($catlist),true);\n\n$category_id = array_column($catlist, 'cat_ID');\nprint_r($category_id);\n</code></pre>\n"
},
{
"answer_id": 270865,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<p>You can always use <code>array_map()</code> </p>\n\n<pre><code>$category_id = array();\n$category_id = array_map( function ($data){\n return $data['cat_ID'];\n }, $catlist);\n</code></pre>\n\n<p>Or wordpress function:</p>\n\n<pre><code> $category_id = array();\n $category_id = wp_list_pluck( $catlist, 'cat_ID' );\n</code></pre>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85288/"
]
| I'm editing the category.php template and I need an array of current category child's.
I'm able to get an array with current category child's but there are too many keys, I'm using the following:
```
//get category ID
$catego = get_category( get_query_var( 'cat' ) );
$cat_id = $catego->cat_ID;
//list current category childs
$catlist = get_categories(
array(
'child_of' => $cat_id,
'orderby' => 'id',
'order' => 'ASC'
) );
```
That gives me the following:
```
Array
(
[0] => WP_Term Object
(
[term_id] => 11
[name] => test1
[slug] => test1
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 3
[filter] => raw
[cat_ID] => 11
[category_count] => 3
[category_description] =>
[cat_name] => test1
[category_nicename] => test1
[category_parent] => 10
)
[1] => WP_Term Object
(
[term_id] => 12
[name] => test2
[slug] => test2
[term_group] => 0
[term_taxonomy_id] => 12
[taxonomy] => category
[description] =>
[parent] => 10
[count] => 1
[filter] => raw
[cat_ID] => 12
[category_count] => 1
[category_description] =>
[cat_name] => test2
[category_nicename] => test2
[category_parent] => 10
)
)
```
Now from this array I want to create an array which will only have the [cat\_ID] key. I've tried the following but it gives me nothing ( <http://php.net/manual/en/function.array-column.php> ):
```
$category_id = array_column($catlist, '[cat_ID]');
print_r($category_id);
```
Any ideas? Thanks in advance. | Try this :
```
// This converts the WP_Term Object to array.
$catlist = json_decode(json_encode($catlist),true);
$category_id = array_column($catlist, 'cat_ID');
print_r($category_id);
``` |
270,886 | <p>I have a caching plugin (WP Rocket) so I am aware of the issues with wp-cron and scheduled posts. So, I disabled <strong>wp-cron</strong> and then set up a system cron. Now, I noticed that when a post is scheduled it's not set to <strong>HH:MM:00</strong> but has some number greater than <strong>0</strong> seconds. So, I set the system cron to run wp-cron at every 5 minutes and 35 minutes past the hour. And still I get missed schedule on posts. I know it runs as I have the output logged which shows a <strong>200</strong> return code plus I see my cache files with timestamps at 5 minutes and 35 minutes past the hour.</p>
<pre><code>define('DISABLE_WP_CRON', true);
</code></pre>
<p>Cron entry (I x'd out my user name. I also have one for 35 minutes with output to wget35.log):</p>
<pre><code>5 * * * * wget -o /home/xxxxx/logs/wget5.log https://www.jennystampsup.com/wp-cron.php?doing_wp_cron 2>/home/xxxxx/logs/wget5.err
</code></pre>
<h2>Update</h2>
<p>Using WP-Control I see that the <code>check_and_publish_future_post</code> event for the post remains as an event after <code>wget</code> runs. I can run it manually from WP-Control and the <code>post_status</code> went to <strong>publish</strong>. If I run <code>wget</code> twice it works. The first <code>wget</code> took one second. The second took 17 seconds, but after it ran the <code>check_and_publish_future_post</code> fired. I will create a script that runs <code>wget</code> several times with some sleep statements and that should do it.</p>
<h2>Update 6/27</h2>
<p>So, posts on my site are scheduled for <strong>7:00:XX</strong>. So, I wrote a script that hits <code>wp-cron.php</code> 10 times, sleeping two seconds in between each hit, and had it kick off in my system cron at <strong>7:01</strong>. And still <code>publish_future_post</code> did not fire. I looked at the WP Cron schedule prior to my script firing and there were 8 other cron events waiting to fire. They all fired. So, I went to Cloud9 and hit <code>wp-cron.php</code> from there. This caused the <code>publish_future_post</code> to fire. The only variables there are it is a different ip and time zone. Those should make no difference as far as I know. This is very puzzling.</p>
| [
{
"answer_id": 270856,
"author": "Senta",
"author_id": 122290,
"author_profile": "https://wordpress.stackexchange.com/users/122290",
"pm_score": 0,
"selected": false,
"text": "<p>A foreach loop works:</p>\n\n<pre><code>$category_id = array();\nforeach ($catlist as $cat){\n $category_id[] = $cat->cat_ID;\n}\n</code></pre>\n"
},
{
"answer_id": 270857,
"author": "Sumesh S",
"author_id": 104736,
"author_profile": "https://wordpress.stackexchange.com/users/104736",
"pm_score": 2,
"selected": true,
"text": "<p>Try this :</p>\n\n<pre><code>// This converts the WP_Term Object to array.\n$catlist = json_decode(json_encode($catlist),true);\n\n$category_id = array_column($catlist, 'cat_ID');\nprint_r($category_id);\n</code></pre>\n"
},
{
"answer_id": 270865,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<p>You can always use <code>array_map()</code> </p>\n\n<pre><code>$category_id = array();\n$category_id = array_map( function ($data){\n return $data['cat_ID'];\n }, $catlist);\n</code></pre>\n\n<p>Or wordpress function:</p>\n\n<pre><code> $category_id = array();\n $category_id = wp_list_pluck( $catlist, 'cat_ID' );\n</code></pre>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122301/"
]
| I have a caching plugin (WP Rocket) so I am aware of the issues with wp-cron and scheduled posts. So, I disabled **wp-cron** and then set up a system cron. Now, I noticed that when a post is scheduled it's not set to **HH:MM:00** but has some number greater than **0** seconds. So, I set the system cron to run wp-cron at every 5 minutes and 35 minutes past the hour. And still I get missed schedule on posts. I know it runs as I have the output logged which shows a **200** return code plus I see my cache files with timestamps at 5 minutes and 35 minutes past the hour.
```
define('DISABLE_WP_CRON', true);
```
Cron entry (I x'd out my user name. I also have one for 35 minutes with output to wget35.log):
```
5 * * * * wget -o /home/xxxxx/logs/wget5.log https://www.jennystampsup.com/wp-cron.php?doing_wp_cron 2>/home/xxxxx/logs/wget5.err
```
Update
------
Using WP-Control I see that the `check_and_publish_future_post` event for the post remains as an event after `wget` runs. I can run it manually from WP-Control and the `post_status` went to **publish**. If I run `wget` twice it works. The first `wget` took one second. The second took 17 seconds, but after it ran the `check_and_publish_future_post` fired. I will create a script that runs `wget` several times with some sleep statements and that should do it.
Update 6/27
-----------
So, posts on my site are scheduled for **7:00:XX**. So, I wrote a script that hits `wp-cron.php` 10 times, sleeping two seconds in between each hit, and had it kick off in my system cron at **7:01**. And still `publish_future_post` did not fire. I looked at the WP Cron schedule prior to my script firing and there were 8 other cron events waiting to fire. They all fired. So, I went to Cloud9 and hit `wp-cron.php` from there. This caused the `publish_future_post` to fire. The only variables there are it is a different ip and time zone. Those should make no difference as far as I know. This is very puzzling. | Try this :
```
// This converts the WP_Term Object to array.
$catlist = json_decode(json_encode($catlist),true);
$category_id = array_column($catlist, 'cat_ID');
print_r($category_id);
``` |
270,901 | <p>I am trying to create a new post with tags. Not having any luck and am not able to find any explanations online of what I may be doing wrong.</p>
<pre><code>methods: {
createPost: function() {
let title = this.newPostTitle;
let content = this.newPostContent;
let postCategories = this.postCategories;
let tags = this.newPostTags.split(",");
let data = {
'title': title,
'content': content,
'status': 'publish',
'categories': postCategories,
'tags': tags,
};
axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e);
console.log(this.errors);
});
this.newPostTitle = '';
this.newPostContent = '';
this.newPostTags = '';
this.postCategories = false;
}
}
</code></pre>
<p>I have the method property above to get the data and post it using VueJS and Axios. What do i need to do to get the tags to post correctly?</p>
<p>I keep getting the following error when I attempt to post</p>
<blockquote>
<p>"tags[0] is not of type integer."</p>
</blockquote>
| [
{
"answer_id": 270905,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like it's expecting tag IDs as integers and you're sending strings. <code>split</code> returns an array of strings, even if those strings are numbers. Instead of using <code>.split</code> try something like this</p>\n\n<pre><code>let tags = JSON.parse(\"[\" + this.newPostTags + \"]\");\n</code></pre>\n\n<p>If you really like split then you would do this:</p>\n\n<pre><code>let tags = this.newPostTags.split(\",\").map(Number);\n</code></pre>\n"
},
{
"answer_id": 324807,
"author": "MirzaP",
"author_id": 105198,
"author_profile": "https://wordpress.stackexchange.com/users/105198",
"pm_score": 0,
"selected": false,
"text": "<p>It's actually expecting a string of comma-separated concatenated tag ids (if anyone is still looking for an answer to this).</p>\n\n<p>Your data would be something like the following, with your split code commented out:</p>\n\n<pre><code>let tags = this.newPostTags; // .split(\",\");\nlet data = {\n 'title': title,\n 'content': content,\n 'status': 'publish',\n 'categories': postCategories,\n 'tags': tags,\n};\n</code></pre>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270901",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121807/"
]
| I am trying to create a new post with tags. Not having any luck and am not able to find any explanations online of what I may be doing wrong.
```
methods: {
createPost: function() {
let title = this.newPostTitle;
let content = this.newPostContent;
let postCategories = this.postCategories;
let tags = this.newPostTags.split(",");
let data = {
'title': title,
'content': content,
'status': 'publish',
'categories': postCategories,
'tags': tags,
};
axios.post("/wp-json/wp/v2/posts/", data, {headers: {'X-WP-Nonce': portal.nonce}})
.then(response => {
console.log(response);
})
.catch(e => {
this.errors.push(e);
console.log(this.errors);
});
this.newPostTitle = '';
this.newPostContent = '';
this.newPostTags = '';
this.postCategories = false;
}
}
```
I have the method property above to get the data and post it using VueJS and Axios. What do i need to do to get the tags to post correctly?
I keep getting the following error when I attempt to post
>
> "tags[0] is not of type integer."
>
>
> | Sounds like it's expecting tag IDs as integers and you're sending strings. `split` returns an array of strings, even if those strings are numbers. Instead of using `.split` try something like this
```
let tags = JSON.parse("[" + this.newPostTags + "]");
```
If you really like split then you would do this:
```
let tags = this.newPostTags.split(",").map(Number);
``` |
270,910 | <p>I apologize in advance for the likely misuse of coding terminology. I am not very skilled when it comes to this. </p>
<p>In a separate website, I have links which when clicked bring up a .pdf of images corresponding to the feature's unique id: <br/>
<code>/Images/{ID}.pdf</code> <br/>
which results in something like <code>example.com/Images/1234.pdf</code> for feature 1234.<br/><br/>
Now let's say someone clicks on the link for feature 1235, but it has no corresponding .pdf. The page currently redirects my generic 404 page I created in wordpress. How do I get it to direct to the specific page <code>example.com/Images/nopdf.pdf</code> for all non-existent pages under the subdomain /Images/? I appreciate in advance for the dumbed-down answers. <br/>
Thanks,<br/>
Deacon</p>
| [
{
"answer_id": 270905,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like it's expecting tag IDs as integers and you're sending strings. <code>split</code> returns an array of strings, even if those strings are numbers. Instead of using <code>.split</code> try something like this</p>\n\n<pre><code>let tags = JSON.parse(\"[\" + this.newPostTags + \"]\");\n</code></pre>\n\n<p>If you really like split then you would do this:</p>\n\n<pre><code>let tags = this.newPostTags.split(\",\").map(Number);\n</code></pre>\n"
},
{
"answer_id": 324807,
"author": "MirzaP",
"author_id": 105198,
"author_profile": "https://wordpress.stackexchange.com/users/105198",
"pm_score": 0,
"selected": false,
"text": "<p>It's actually expecting a string of comma-separated concatenated tag ids (if anyone is still looking for an answer to this).</p>\n\n<p>Your data would be something like the following, with your split code commented out:</p>\n\n<pre><code>let tags = this.newPostTags; // .split(\",\");\nlet data = {\n 'title': title,\n 'content': content,\n 'status': 'publish',\n 'categories': postCategories,\n 'tags': tags,\n};\n</code></pre>\n"
}
]
| 2017/06/21 | [
"https://wordpress.stackexchange.com/questions/270910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122313/"
]
| I apologize in advance for the likely misuse of coding terminology. I am not very skilled when it comes to this.
In a separate website, I have links which when clicked bring up a .pdf of images corresponding to the feature's unique id:
`/Images/{ID}.pdf`
which results in something like `example.com/Images/1234.pdf` for feature 1234.
Now let's say someone clicks on the link for feature 1235, but it has no corresponding .pdf. The page currently redirects my generic 404 page I created in wordpress. How do I get it to direct to the specific page `example.com/Images/nopdf.pdf` for all non-existent pages under the subdomain /Images/? I appreciate in advance for the dumbed-down answers.
Thanks,
Deacon | Sounds like it's expecting tag IDs as integers and you're sending strings. `split` returns an array of strings, even if those strings are numbers. Instead of using `.split` try something like this
```
let tags = JSON.parse("[" + this.newPostTags + "]");
```
If you really like split then you would do this:
```
let tags = this.newPostTags.split(",").map(Number);
``` |
270,930 | <p>The idea is to immediately show the post matching the search term.
The search term will be alphanumeric and unique for each post (set as title).
It could override search in content (for performance), I just need the title.</p>
<p>The search will be provided through a barcode reader, so it will be unique and precise.</p>
<p>I'm trying to immediately show the post, not the search results page, but I can't figure how.</p>
| [
{
"answer_id": 270933,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 0,
"selected": false,
"text": "<p>Custom <code>template</code> where You have custom <code>query</code>. This <code>query</code> search only one <code>post</code> and <code>template</code> shows this only <code>post</code>. </p>\n"
},
{
"answer_id": 270940,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a solution that I came up with that uses a hidden field on the search form which we will later check in our filters to modify WP's default search/redirect behavior.</p>\n\n<p>This is the search form I used. Note the addition of the hidden field <code>barcode-reader</code> with a value of <code>1</code>. I added the search form to a page template for testing and demonstration purposes.</p>\n\n<pre><code><form role=\"search\" method=\"get\" class=\"search-form\" action=\"<?php echo esc_attr( home_url( '/' ) ); ?>\">\n <label>\n <span class=\"screen-reader-text\"><?php echo _x( 'Search for:', 'screen reader search label', 'textdomain' ); ?></span>\n <div class=\"input-group\">\n <input type=\"search\" class=\"search-field input-group-field\" placeholder=\"<?php echo esc_attr_x( 'Search...', 'search placeholder', 'textdomain' ); ?>\" value=\"<?php echo get_search_query(); ?>\" name=\"s\" title=\"<?php echo esc_attr_x( 'Search for:', 'textdomain' ); ?>\" />\n\n <input type=\"hidden\" value=\"1\" name=\"barcode-reader\" />\n\n <div class=\"input-group-button\">\n <button type=\"submit\" class=\"search-submit button\" value=\"<?php echo esc_attr_x( 'Search', 'search button', 'textdomain' ); ?>\">Search</button>\n </div>\n </div>\n </label>\n</form>\n</code></pre>\n\n<p>(<em>It's not clear from the original post, but from the research I've done, it should be possible for the barcode reader to send a parameter via <code>$_GET</code> which could be used instead of the hidden field I've used for testing.)</em></p>\n\n<p>Here, we will check if this search is being performed by the barcode scanner using the helper function <code>wpse_is_barcode_search()</code>. The helper function is used so that we don't have to duplicate the logic across the multiple hooks that are used in this implementation.</p>\n\n<p>If we are doing a search using the scanner, we wire up our <code>posts_search</code> filter and do some modifications to the <code>WP_Query</code> instance before the query is performed.</p>\n\n<pre><code>/**\n * Wire up our posts_search filter and change the $query.\n * \n * @param WP_Query $query The WP_Query instance (passed by reference).\n */\nadd_action( 'pre_get_posts', 'wpse_barcode_search_pre_get_posts' );\nfunction wpse_barcode_search_pre_get_posts( $query ) {\n // Bail if this search is not performed by the barcode scanner.\n if ( ! wpse_is_barcode_search( $query ) ) {\n return;\n }\n\n // Wire up the filter to modify the search SQL.\n add_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );\n\n // Set posts_per_page to one since we're only looking for an exact match anyway.\n $query->set( 'posts_per_page', 1 );\n\n // (suggestion) Limit search to a particular post type.\n // $query->set( 'post_type', array( 'product', ) );\n}\n</code></pre>\n\n<p>Here is the filter that actually modifies the search SQL. Since we only want this to fire once, the filter is immediately unooked.</p>\n\n<pre><code>/**\n * Modify search query so that the search term looks for an exact\n * match with the post title.\n *\n * @param string $search Search SQL for WHERE clause.\n * @param WP_Query $wp_query The current WP_Query object.\n */\nfunction wpse_barcode_posts_search( $search, $wp_query ) {\n // We only want the search filter to fire once, so unhook it.\n remove_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );\n\n // Change the search SQL so that it checks if the search is equal to the post title.\n $search = \" AND (wp_posts.post_title = '\" . esc_sql( $wp_query->query_vars['s'] ) . \"')\";\n\n return $search;\n}\n</code></pre>\n\n<p>This code redirects the user to the permalink of our found post rather than the search results page.</p>\n\n<pre><code>/**\n * Redirect to the permalink of the searched item if it was found using\n * the barcode search.\n *\n * @link https://wordpress.stackexchange.com/a/128578/2807\n */\nadd_action( 'template_redirect', 'wpse_barcode_search_success_redirect' );\nfunction wpse_barcode_search_success_redirect() {\n global $wp_query;\n if ( ! wpse_is_barcode_search( $wp_query ) ) {\n return;\n }\n\n // If we have a post, redirect to it.\n if ( '1' === $wp_query->found_posts ) {\n wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );\n exit;\n }\n}\n</code></pre>\n\n<p>Finally, here is the helper function used to determine if we are performing a search using the barcode scanner. This should be modified so that it works with the scanner used ( particularly, the check using <code>$_REQUEST['barcode-reader']</code> ).</p>\n\n<pre><code>/**\n * Helper function used to determine if a search is performed using\n * the barcode scanner.\n *\n * @uses array $_REQUEST\n * @param object $query\n * @return bool\n */\nfunction wpse_is_barcode_search( $query ) {\n // Bail if $query is not an instance of WP_Query.\n if ( ! ( $query instanceof WP_Query ) ) {\n return false;\n }\n\n // Bail if this is the admin area. \n if ( $query->is_admin() ) {\n return false;\n }\n\n // Bail if this is not the search page or main query.\n if ( ! $query->is_search() || ! $query->is_main_query() ) {\n return false;\n }\n\n // Bail if this is not our special barcode search.\n if ( ! isset( $_REQUEST['barcode-reader'] ) || '1' !== $_REQUEST['barcode-reader'] ) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122334/"
]
| The idea is to immediately show the post matching the search term.
The search term will be alphanumeric and unique for each post (set as title).
It could override search in content (for performance), I just need the title.
The search will be provided through a barcode reader, so it will be unique and precise.
I'm trying to immediately show the post, not the search results page, but I can't figure how. | Here's a solution that I came up with that uses a hidden field on the search form which we will later check in our filters to modify WP's default search/redirect behavior.
This is the search form I used. Note the addition of the hidden field `barcode-reader` with a value of `1`. I added the search form to a page template for testing and demonstration purposes.
```
<form role="search" method="get" class="search-form" action="<?php echo esc_attr( home_url( '/' ) ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'screen reader search label', 'textdomain' ); ?></span>
<div class="input-group">
<input type="search" class="search-field input-group-field" placeholder="<?php echo esc_attr_x( 'Search...', 'search placeholder', 'textdomain' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'textdomain' ); ?>" />
<input type="hidden" value="1" name="barcode-reader" />
<div class="input-group-button">
<button type="submit" class="search-submit button" value="<?php echo esc_attr_x( 'Search', 'search button', 'textdomain' ); ?>">Search</button>
</div>
</div>
</label>
</form>
```
(*It's not clear from the original post, but from the research I've done, it should be possible for the barcode reader to send a parameter via `$_GET` which could be used instead of the hidden field I've used for testing.)*
Here, we will check if this search is being performed by the barcode scanner using the helper function `wpse_is_barcode_search()`. The helper function is used so that we don't have to duplicate the logic across the multiple hooks that are used in this implementation.
If we are doing a search using the scanner, we wire up our `posts_search` filter and do some modifications to the `WP_Query` instance before the query is performed.
```
/**
* Wire up our posts_search filter and change the $query.
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
add_action( 'pre_get_posts', 'wpse_barcode_search_pre_get_posts' );
function wpse_barcode_search_pre_get_posts( $query ) {
// Bail if this search is not performed by the barcode scanner.
if ( ! wpse_is_barcode_search( $query ) ) {
return;
}
// Wire up the filter to modify the search SQL.
add_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );
// Set posts_per_page to one since we're only looking for an exact match anyway.
$query->set( 'posts_per_page', 1 );
// (suggestion) Limit search to a particular post type.
// $query->set( 'post_type', array( 'product', ) );
}
```
Here is the filter that actually modifies the search SQL. Since we only want this to fire once, the filter is immediately unooked.
```
/**
* Modify search query so that the search term looks for an exact
* match with the post title.
*
* @param string $search Search SQL for WHERE clause.
* @param WP_Query $wp_query The current WP_Query object.
*/
function wpse_barcode_posts_search( $search, $wp_query ) {
// We only want the search filter to fire once, so unhook it.
remove_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );
// Change the search SQL so that it checks if the search is equal to the post title.
$search = " AND (wp_posts.post_title = '" . esc_sql( $wp_query->query_vars['s'] ) . "')";
return $search;
}
```
This code redirects the user to the permalink of our found post rather than the search results page.
```
/**
* Redirect to the permalink of the searched item if it was found using
* the barcode search.
*
* @link https://wordpress.stackexchange.com/a/128578/2807
*/
add_action( 'template_redirect', 'wpse_barcode_search_success_redirect' );
function wpse_barcode_search_success_redirect() {
global $wp_query;
if ( ! wpse_is_barcode_search( $wp_query ) ) {
return;
}
// If we have a post, redirect to it.
if ( '1' === $wp_query->found_posts ) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
```
Finally, here is the helper function used to determine if we are performing a search using the barcode scanner. This should be modified so that it works with the scanner used ( particularly, the check using `$_REQUEST['barcode-reader']` ).
```
/**
* Helper function used to determine if a search is performed using
* the barcode scanner.
*
* @uses array $_REQUEST
* @param object $query
* @return bool
*/
function wpse_is_barcode_search( $query ) {
// Bail if $query is not an instance of WP_Query.
if ( ! ( $query instanceof WP_Query ) ) {
return false;
}
// Bail if this is the admin area.
if ( $query->is_admin() ) {
return false;
}
// Bail if this is not the search page or main query.
if ( ! $query->is_search() || ! $query->is_main_query() ) {
return false;
}
// Bail if this is not our special barcode search.
if ( ! isset( $_REQUEST['barcode-reader'] ) || '1' !== $_REQUEST['barcode-reader'] ) {
return false;
}
return true;
}
``` |
270,934 | <p>I have cloned the "proceed to cart" button and float on the upper-right corner on the Woocommerce cart page. However I want this button to appear only when the browser is compressed (simulating mobile display), but go away when browser is stretched to the size of PC display. How to do it?</p>
<p>Here is the code I came up, but its not working.</p>
<pre><code>if(width <= 320){
add_action( 'woocommerce_before_cart', 'move_proceed_button' );
function move_proceed_button( $checkout ) {
echo '<a href="' . esc_url( WC()->cart->get_checkout_url() ) . '"
class="checkout-button button alt wc-forward" >' . __( 'Proceed to
Checkout', 'woocommerce' ) . '</a>';
}
} else
if(width > 325){
remove_action( 'woocommerce_before_cart', 'move_proceed_button' );
});
?>
</code></pre>
| [
{
"answer_id": 270933,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 0,
"selected": false,
"text": "<p>Custom <code>template</code> where You have custom <code>query</code>. This <code>query</code> search only one <code>post</code> and <code>template</code> shows this only <code>post</code>. </p>\n"
},
{
"answer_id": 270940,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a solution that I came up with that uses a hidden field on the search form which we will later check in our filters to modify WP's default search/redirect behavior.</p>\n\n<p>This is the search form I used. Note the addition of the hidden field <code>barcode-reader</code> with a value of <code>1</code>. I added the search form to a page template for testing and demonstration purposes.</p>\n\n<pre><code><form role=\"search\" method=\"get\" class=\"search-form\" action=\"<?php echo esc_attr( home_url( '/' ) ); ?>\">\n <label>\n <span class=\"screen-reader-text\"><?php echo _x( 'Search for:', 'screen reader search label', 'textdomain' ); ?></span>\n <div class=\"input-group\">\n <input type=\"search\" class=\"search-field input-group-field\" placeholder=\"<?php echo esc_attr_x( 'Search...', 'search placeholder', 'textdomain' ); ?>\" value=\"<?php echo get_search_query(); ?>\" name=\"s\" title=\"<?php echo esc_attr_x( 'Search for:', 'textdomain' ); ?>\" />\n\n <input type=\"hidden\" value=\"1\" name=\"barcode-reader\" />\n\n <div class=\"input-group-button\">\n <button type=\"submit\" class=\"search-submit button\" value=\"<?php echo esc_attr_x( 'Search', 'search button', 'textdomain' ); ?>\">Search</button>\n </div>\n </div>\n </label>\n</form>\n</code></pre>\n\n<p>(<em>It's not clear from the original post, but from the research I've done, it should be possible for the barcode reader to send a parameter via <code>$_GET</code> which could be used instead of the hidden field I've used for testing.)</em></p>\n\n<p>Here, we will check if this search is being performed by the barcode scanner using the helper function <code>wpse_is_barcode_search()</code>. The helper function is used so that we don't have to duplicate the logic across the multiple hooks that are used in this implementation.</p>\n\n<p>If we are doing a search using the scanner, we wire up our <code>posts_search</code> filter and do some modifications to the <code>WP_Query</code> instance before the query is performed.</p>\n\n<pre><code>/**\n * Wire up our posts_search filter and change the $query.\n * \n * @param WP_Query $query The WP_Query instance (passed by reference).\n */\nadd_action( 'pre_get_posts', 'wpse_barcode_search_pre_get_posts' );\nfunction wpse_barcode_search_pre_get_posts( $query ) {\n // Bail if this search is not performed by the barcode scanner.\n if ( ! wpse_is_barcode_search( $query ) ) {\n return;\n }\n\n // Wire up the filter to modify the search SQL.\n add_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );\n\n // Set posts_per_page to one since we're only looking for an exact match anyway.\n $query->set( 'posts_per_page', 1 );\n\n // (suggestion) Limit search to a particular post type.\n // $query->set( 'post_type', array( 'product', ) );\n}\n</code></pre>\n\n<p>Here is the filter that actually modifies the search SQL. Since we only want this to fire once, the filter is immediately unooked.</p>\n\n<pre><code>/**\n * Modify search query so that the search term looks for an exact\n * match with the post title.\n *\n * @param string $search Search SQL for WHERE clause.\n * @param WP_Query $wp_query The current WP_Query object.\n */\nfunction wpse_barcode_posts_search( $search, $wp_query ) {\n // We only want the search filter to fire once, so unhook it.\n remove_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );\n\n // Change the search SQL so that it checks if the search is equal to the post title.\n $search = \" AND (wp_posts.post_title = '\" . esc_sql( $wp_query->query_vars['s'] ) . \"')\";\n\n return $search;\n}\n</code></pre>\n\n<p>This code redirects the user to the permalink of our found post rather than the search results page.</p>\n\n<pre><code>/**\n * Redirect to the permalink of the searched item if it was found using\n * the barcode search.\n *\n * @link https://wordpress.stackexchange.com/a/128578/2807\n */\nadd_action( 'template_redirect', 'wpse_barcode_search_success_redirect' );\nfunction wpse_barcode_search_success_redirect() {\n global $wp_query;\n if ( ! wpse_is_barcode_search( $wp_query ) ) {\n return;\n }\n\n // If we have a post, redirect to it.\n if ( '1' === $wp_query->found_posts ) {\n wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );\n exit;\n }\n}\n</code></pre>\n\n<p>Finally, here is the helper function used to determine if we are performing a search using the barcode scanner. This should be modified so that it works with the scanner used ( particularly, the check using <code>$_REQUEST['barcode-reader']</code> ).</p>\n\n<pre><code>/**\n * Helper function used to determine if a search is performed using\n * the barcode scanner.\n *\n * @uses array $_REQUEST\n * @param object $query\n * @return bool\n */\nfunction wpse_is_barcode_search( $query ) {\n // Bail if $query is not an instance of WP_Query.\n if ( ! ( $query instanceof WP_Query ) ) {\n return false;\n }\n\n // Bail if this is the admin area. \n if ( $query->is_admin() ) {\n return false;\n }\n\n // Bail if this is not the search page or main query.\n if ( ! $query->is_search() || ! $query->is_main_query() ) {\n return false;\n }\n\n // Bail if this is not our special barcode search.\n if ( ! isset( $_REQUEST['barcode-reader'] ) || '1' !== $_REQUEST['barcode-reader'] ) {\n return false;\n }\n\n return true;\n}\n</code></pre>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122069/"
]
| I have cloned the "proceed to cart" button and float on the upper-right corner on the Woocommerce cart page. However I want this button to appear only when the browser is compressed (simulating mobile display), but go away when browser is stretched to the size of PC display. How to do it?
Here is the code I came up, but its not working.
```
if(width <= 320){
add_action( 'woocommerce_before_cart', 'move_proceed_button' );
function move_proceed_button( $checkout ) {
echo '<a href="' . esc_url( WC()->cart->get_checkout_url() ) . '"
class="checkout-button button alt wc-forward" >' . __( 'Proceed to
Checkout', 'woocommerce' ) . '</a>';
}
} else
if(width > 325){
remove_action( 'woocommerce_before_cart', 'move_proceed_button' );
});
?>
``` | Here's a solution that I came up with that uses a hidden field on the search form which we will later check in our filters to modify WP's default search/redirect behavior.
This is the search form I used. Note the addition of the hidden field `barcode-reader` with a value of `1`. I added the search form to a page template for testing and demonstration purposes.
```
<form role="search" method="get" class="search-form" action="<?php echo esc_attr( home_url( '/' ) ); ?>">
<label>
<span class="screen-reader-text"><?php echo _x( 'Search for:', 'screen reader search label', 'textdomain' ); ?></span>
<div class="input-group">
<input type="search" class="search-field input-group-field" placeholder="<?php echo esc_attr_x( 'Search...', 'search placeholder', 'textdomain' ); ?>" value="<?php echo get_search_query(); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'textdomain' ); ?>" />
<input type="hidden" value="1" name="barcode-reader" />
<div class="input-group-button">
<button type="submit" class="search-submit button" value="<?php echo esc_attr_x( 'Search', 'search button', 'textdomain' ); ?>">Search</button>
</div>
</div>
</label>
</form>
```
(*It's not clear from the original post, but from the research I've done, it should be possible for the barcode reader to send a parameter via `$_GET` which could be used instead of the hidden field I've used for testing.)*
Here, we will check if this search is being performed by the barcode scanner using the helper function `wpse_is_barcode_search()`. The helper function is used so that we don't have to duplicate the logic across the multiple hooks that are used in this implementation.
If we are doing a search using the scanner, we wire up our `posts_search` filter and do some modifications to the `WP_Query` instance before the query is performed.
```
/**
* Wire up our posts_search filter and change the $query.
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
add_action( 'pre_get_posts', 'wpse_barcode_search_pre_get_posts' );
function wpse_barcode_search_pre_get_posts( $query ) {
// Bail if this search is not performed by the barcode scanner.
if ( ! wpse_is_barcode_search( $query ) ) {
return;
}
// Wire up the filter to modify the search SQL.
add_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );
// Set posts_per_page to one since we're only looking for an exact match anyway.
$query->set( 'posts_per_page', 1 );
// (suggestion) Limit search to a particular post type.
// $query->set( 'post_type', array( 'product', ) );
}
```
Here is the filter that actually modifies the search SQL. Since we only want this to fire once, the filter is immediately unooked.
```
/**
* Modify search query so that the search term looks for an exact
* match with the post title.
*
* @param string $search Search SQL for WHERE clause.
* @param WP_Query $wp_query The current WP_Query object.
*/
function wpse_barcode_posts_search( $search, $wp_query ) {
// We only want the search filter to fire once, so unhook it.
remove_filter( 'posts_search', 'wpse_barcode_posts_search', 10, 2 );
// Change the search SQL so that it checks if the search is equal to the post title.
$search = " AND (wp_posts.post_title = '" . esc_sql( $wp_query->query_vars['s'] ) . "')";
return $search;
}
```
This code redirects the user to the permalink of our found post rather than the search results page.
```
/**
* Redirect to the permalink of the searched item if it was found using
* the barcode search.
*
* @link https://wordpress.stackexchange.com/a/128578/2807
*/
add_action( 'template_redirect', 'wpse_barcode_search_success_redirect' );
function wpse_barcode_search_success_redirect() {
global $wp_query;
if ( ! wpse_is_barcode_search( $wp_query ) ) {
return;
}
// If we have a post, redirect to it.
if ( '1' === $wp_query->found_posts ) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
```
Finally, here is the helper function used to determine if we are performing a search using the barcode scanner. This should be modified so that it works with the scanner used ( particularly, the check using `$_REQUEST['barcode-reader']` ).
```
/**
* Helper function used to determine if a search is performed using
* the barcode scanner.
*
* @uses array $_REQUEST
* @param object $query
* @return bool
*/
function wpse_is_barcode_search( $query ) {
// Bail if $query is not an instance of WP_Query.
if ( ! ( $query instanceof WP_Query ) ) {
return false;
}
// Bail if this is the admin area.
if ( $query->is_admin() ) {
return false;
}
// Bail if this is not the search page or main query.
if ( ! $query->is_search() || ! $query->is_main_query() ) {
return false;
}
// Bail if this is not our special barcode search.
if ( ! isset( $_REQUEST['barcode-reader'] ) || '1' !== $_REQUEST['barcode-reader'] ) {
return false;
}
return true;
}
``` |
270,937 | <p>I'm learning about coding plugin.</p>
<p>I trying to create a form in plugin page and it can send mail.</p>
<p>This is my code, but it doesn't work(I did not receive email and did not show any error).</p>
<pre><code>add_action('admin_menu', 'add_contact_us_page');
function add_contact_us_page() {
add_menu_page(
__( 'Contact Us', 'textdomain' ),
__( 'Contact Us','textdomain' ),
'manage_options',
'support_form_page',
'support_form',
''
);
}
function support_form() {
?>
<form action="" method="post" enctype="text/plain">
Name:<br>
<input type="text" name="name"><br>
E-mail:<br>
<input type="text" name="email"><br>
Message:<br>
<input type="text" name="message" size="50"><br><br>
<input type="submit" value="save">
</form>
<?php
}
if ( isset($_POST["submit"])) {
do_action('my_phpmailer_example');
}
add_action( 'phpmailer_init', 'my_phpmailer_example' );
function my_phpmailer_example( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.sendgrid.net';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 587;
$phpmailer->Username = '****';
$phpmailer->Password = '****';
$phpmailer->SMTPSecure = "tls";
$phpmailer->From = "[email protected]";
$phpmailer->FromName = "Your Name";
$phpmailer->Subject = "Subject Text";
$phpmailer->Body = "<i>Mail body in HTML</i>";
$phpmailer->AltBody = "This is the plain text version of the email content";
$phpmailer->AddAddress("[email protected]", "name");
$phpmailer->SMTPDebug = true;
$smtp_debug = ob_get_clean();
if(!$phpmailer->send())
{
echo "Mailer Error: " . $phpmailer->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
echo $smtp_debug;
}
}
</code></pre>
<p>Please help, thanks!</p>
| [
{
"answer_id": 270943,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 2,
"selected": true,
"text": "<p>I suggest you first of all to separate code from markup, especially dividing your executing file like the function <code>support_form()</code>.</p>\n\n<p>Next, please try to send email without form with hard coded message. It is possible you have mis-configuration on your server if you developing on local machine.</p>\n\n<p>And finally, you should fill <code>action</code> attribute for <code><form></code> tag. And that must refer to the executable script. Otherwise it tries to execute you homepage where this code is absent. If you are not planning to separate your markup and code I suppose you should link your action to the file that contains this script. When that happens, your code </p>\n\n<pre><code>if ( isset($_POST[\"submit\"])) {\n do_action('my_phpmailer_example');\n}\n</code></pre>\n\n<p>will execute.</p>\n"
},
{
"answer_id": 368792,
"author": "Brian Layman",
"author_id": 2785,
"author_profile": "https://wordpress.stackexchange.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "<p>Just for the record, in case anyone looks at this later, there are a few issues with the original code. \nThe first is with this line:</p>\n\n<pre><code>do_action('my_phpmailer_example');\n</code></pre>\n\n<p>do_action() expects the name of an action/hook and will execute all of the functions associated with that hook. In you're line, you called it with the name of the function you defined, not the name of the action. Usually you don't ever have to use do_action(). WordPress itself calls the 'phpmailer_init' action at the appropriate time. In your case, you've used the name of the function you were trying to call. So you told WP to do was to look for a hook named 'my_phpmailer_example' and execute all actions added to it. That's why your line did nothing when the form was submitted.</p>\n\n<p>Second, you're combining two different tasks. You want to take the sending code out of your function that you've associated with the 'phpmailer_init' hook. That's only used for initializing phpmailer - setting the servers and from values, that sort of thing. the 'phpmailer_init' action will be executed every time WordPress prepares itself to send emails. And you don't want your plugin sending your emails when WordPress even just starts up. So take all of the stuff that doesn't apply for EVERY email WordPress sends out out of my_phpmailer_example().</p>\n\n<p>Third, what you need is the wp_mail function. That would look something like this:</p>\n\n<pre><code>if ( isset( $_POST['submit'] ) ) {\n $to = '[email protected]';\n $subject = 'The subject';\n $body = 'The email body content';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n wp_mail( $to, $subject, $body, $headers );\n}\n</code></pre>\n\n<p>But you would use your form submissions. You can read about that function here: <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n\n<p>Fourth, you need to build in security into your form or everyone and their uncle will use it to send spam. Look up how to use nonces on WordPress forms and current_user_can() and how to properly filter what your user has supplied, if you going to allow html emails.</p>\n\n<p>Those topics should get anyone looking into this pointed in the right direction.</p>\n\n<p>Cheers all!</p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118364/"
]
| I'm learning about coding plugin.
I trying to create a form in plugin page and it can send mail.
This is my code, but it doesn't work(I did not receive email and did not show any error).
```
add_action('admin_menu', 'add_contact_us_page');
function add_contact_us_page() {
add_menu_page(
__( 'Contact Us', 'textdomain' ),
__( 'Contact Us','textdomain' ),
'manage_options',
'support_form_page',
'support_form',
''
);
}
function support_form() {
?>
<form action="" method="post" enctype="text/plain">
Name:<br>
<input type="text" name="name"><br>
E-mail:<br>
<input type="text" name="email"><br>
Message:<br>
<input type="text" name="message" size="50"><br><br>
<input type="submit" value="save">
</form>
<?php
}
if ( isset($_POST["submit"])) {
do_action('my_phpmailer_example');
}
add_action( 'phpmailer_init', 'my_phpmailer_example' );
function my_phpmailer_example( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.sendgrid.net';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 587;
$phpmailer->Username = '****';
$phpmailer->Password = '****';
$phpmailer->SMTPSecure = "tls";
$phpmailer->From = "[email protected]";
$phpmailer->FromName = "Your Name";
$phpmailer->Subject = "Subject Text";
$phpmailer->Body = "<i>Mail body in HTML</i>";
$phpmailer->AltBody = "This is the plain text version of the email content";
$phpmailer->AddAddress("[email protected]", "name");
$phpmailer->SMTPDebug = true;
$smtp_debug = ob_get_clean();
if(!$phpmailer->send())
{
echo "Mailer Error: " . $phpmailer->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
echo $smtp_debug;
}
}
```
Please help, thanks! | I suggest you first of all to separate code from markup, especially dividing your executing file like the function `support_form()`.
Next, please try to send email without form with hard coded message. It is possible you have mis-configuration on your server if you developing on local machine.
And finally, you should fill `action` attribute for `<form>` tag. And that must refer to the executable script. Otherwise it tries to execute you homepage where this code is absent. If you are not planning to separate your markup and code I suppose you should link your action to the file that contains this script. When that happens, your code
```
if ( isset($_POST["submit"])) {
do_action('my_phpmailer_example');
}
```
will execute. |
270,951 | <p>My footer is wide in my worspress page. But in one page it is not wide. How can i fix this problem. I use Simple Job Board plugin.</p>
<p>This is the page with problem.
<a href="http://balikesirkolej.com/jobs/sinif-ogretmeni/" rel="nofollow noreferrer">http://balikesirkolej.com/jobs/sinif-ogretmeni/</a></p>
<p>This is the page without problem
<a href="http://balikesirkolej.com/is-basvurusu/" rel="nofollow noreferrer">http://balikesirkolej.com/is-basvurusu/</a></p>
| [
{
"answer_id": 270943,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 2,
"selected": true,
"text": "<p>I suggest you first of all to separate code from markup, especially dividing your executing file like the function <code>support_form()</code>.</p>\n\n<p>Next, please try to send email without form with hard coded message. It is possible you have mis-configuration on your server if you developing on local machine.</p>\n\n<p>And finally, you should fill <code>action</code> attribute for <code><form></code> tag. And that must refer to the executable script. Otherwise it tries to execute you homepage where this code is absent. If you are not planning to separate your markup and code I suppose you should link your action to the file that contains this script. When that happens, your code </p>\n\n<pre><code>if ( isset($_POST[\"submit\"])) {\n do_action('my_phpmailer_example');\n}\n</code></pre>\n\n<p>will execute.</p>\n"
},
{
"answer_id": 368792,
"author": "Brian Layman",
"author_id": 2785,
"author_profile": "https://wordpress.stackexchange.com/users/2785",
"pm_score": 0,
"selected": false,
"text": "<p>Just for the record, in case anyone looks at this later, there are a few issues with the original code. \nThe first is with this line:</p>\n\n<pre><code>do_action('my_phpmailer_example');\n</code></pre>\n\n<p>do_action() expects the name of an action/hook and will execute all of the functions associated with that hook. In you're line, you called it with the name of the function you defined, not the name of the action. Usually you don't ever have to use do_action(). WordPress itself calls the 'phpmailer_init' action at the appropriate time. In your case, you've used the name of the function you were trying to call. So you told WP to do was to look for a hook named 'my_phpmailer_example' and execute all actions added to it. That's why your line did nothing when the form was submitted.</p>\n\n<p>Second, you're combining two different tasks. You want to take the sending code out of your function that you've associated with the 'phpmailer_init' hook. That's only used for initializing phpmailer - setting the servers and from values, that sort of thing. the 'phpmailer_init' action will be executed every time WordPress prepares itself to send emails. And you don't want your plugin sending your emails when WordPress even just starts up. So take all of the stuff that doesn't apply for EVERY email WordPress sends out out of my_phpmailer_example().</p>\n\n<p>Third, what you need is the wp_mail function. That would look something like this:</p>\n\n<pre><code>if ( isset( $_POST['submit'] ) ) {\n $to = '[email protected]';\n $subject = 'The subject';\n $body = 'The email body content';\n $headers = array('Content-Type: text/html; charset=UTF-8');\n wp_mail( $to, $subject, $body, $headers );\n}\n</code></pre>\n\n<p>But you would use your form submissions. You can read about that function here: <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n\n<p>Fourth, you need to build in security into your form or everyone and their uncle will use it to send spam. Look up how to use nonces on WordPress forms and current_user_can() and how to properly filter what your user has supplied, if you going to allow html emails.</p>\n\n<p>Those topics should get anyone looking into this pointed in the right direction.</p>\n\n<p>Cheers all!</p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122348/"
]
| My footer is wide in my worspress page. But in one page it is not wide. How can i fix this problem. I use Simple Job Board plugin.
This is the page with problem.
<http://balikesirkolej.com/jobs/sinif-ogretmeni/>
This is the page without problem
<http://balikesirkolej.com/is-basvurusu/> | I suggest you first of all to separate code from markup, especially dividing your executing file like the function `support_form()`.
Next, please try to send email without form with hard coded message. It is possible you have mis-configuration on your server if you developing on local machine.
And finally, you should fill `action` attribute for `<form>` tag. And that must refer to the executable script. Otherwise it tries to execute you homepage where this code is absent. If you are not planning to separate your markup and code I suppose you should link your action to the file that contains this script. When that happens, your code
```
if ( isset($_POST["submit"])) {
do_action('my_phpmailer_example');
}
```
will execute. |
270,966 | <p>i placed 'Gravity Forms User Registration Add-On's login widget in a page that registered users can login to my site.
how do i redirect users to previous page that came from to login page after they submit login form? </p>
| [
{
"answer_id": 270976,
"author": "Pirlanta Web",
"author_id": 122358,
"author_profile": "https://wordpress.stackexchange.com/users/122358",
"pm_score": 0,
"selected": false,
"text": "<p>by help of gravity forms documentation i wrote this code , but it doesn't work!</p>\n\n<blockquote>\n <p><a href=\"https://www.gravityhelp.com/documentation/article/gform_user_registration_login_redirect_url/\" rel=\"nofollow noreferrer\">https://www.gravityhelp.com/documentation/article/gform_user_registration_login_redirect_url/</a></p>\n</blockquote>\n\n<pre><code>function redirect_mylogin ( $login_redirect, $sign_on ) {\n//here is redirection code\n$login_redirect = esc_url( $_SERVER['HTTP_REFERER'] );\nreturn $login_redirect; }\nadd_filter( 'gform_user_registration_login_redirect_url','redirect_mylogin', 10, 2 );\n</code></pre>\n\n<p>please help!</p>\n"
},
{
"answer_id": 271851,
"author": "Pirlanta Web",
"author_id": 122358,
"author_profile": "https://wordpress.stackexchange.com/users/122358",
"pm_score": 2,
"selected": true,
"text": "<p>here is the solution : </p>\n\n<pre><code>add_filter('gform_user_registration_login_args','registration_login_args',10, 1);\nfunction registration_login_args( $args )\n{ \n$args['login_redirect'] = rgpost('login_redirect') ? rgpost('login_redirect') : RGForms::get('HTTP_REFERER', $_SERVER);\nreturn $args;\n}\n</code></pre>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270966",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122358/"
]
| i placed 'Gravity Forms User Registration Add-On's login widget in a page that registered users can login to my site.
how do i redirect users to previous page that came from to login page after they submit login form? | here is the solution :
```
add_filter('gform_user_registration_login_args','registration_login_args',10, 1);
function registration_login_args( $args )
{
$args['login_redirect'] = rgpost('login_redirect') ? rgpost('login_redirect') : RGForms::get('HTTP_REFERER', $_SERVER);
return $args;
}
``` |
270,974 | <p>I am trying to show cross sells on a single product page rather than in the cart:</p>
<p>So far I've tried the following code:</p>
<pre><code><?php do_action( 'woocommerce_after_single_product_summary_data_tabs' ); ?>
<?php if ( $product->get_upsell_ids() ) : ?>
<div class="single_product_summary_upsell">
<?php do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
</div><!-- .single_product_summary_upsells -->
<?php endif; ?>
<?php if ( $product->get_cross_sell_ids() ) : ?>
<div class="single_product_summary_upsell">
<?php do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
</div><!-- .single_product_summary_upsells -->
<?php endif; ?>
<div class="single_product_summary_related">
<?php do_action( 'woocommerce_after_single_product_summary_related_products' ); ?>
</div><!-- .single_product_summary_related -->
</div><!-- .columns -->
</code></pre>
<p>However this will only show upsells below upsells, so it's just the same content twice. I am not sure on what action to use instead of </p>
<pre><code>do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
</code></pre>
| [
{
"answer_id": 270975,
"author": "Alpesh Rathod",
"author_id": 71458,
"author_profile": "https://wordpress.stackexchange.com/users/71458",
"pm_score": 1,
"selected": false,
"text": "<p>find this code and remove it </p>\n\n<p>1: get the ids of the cross sell products using the ‘_crosssell_ids’ meta key.</p>\n\n<pre><code><?php\n\n/* crossells */\n\n$crosssell_ids = get_post_meta( get_the_ID(), '_crosssell_ids' ); \n$crosssell_ids=$crosssell_ids[0];\n\n?>\n</code></pre>\n\n<ol start=\"2\">\n<li>Loop through the products by id</li>\n</ol>\n\n<hr>\n\n<pre><code>if(count($crosssell_ids)>0){\n$args = array( 'post_type' => 'product', 'posts_per_page' => 10, 'post__in' => $crosssell_ids );\n$loop = new WP_Query( $args );\nwhile ( $loop->have_posts() ) : $loop->the_post();\n?><a href='<?php the_permalink(); ?>'><?php\nthe_post_thumbnail( 'thumbnail' );\nthe_title();\n?></a><?php\nendwhile;\n}\n</code></pre>\n"
},
{
"answer_id": 271071,
"author": "itzmekhokan",
"author_id": 106821,
"author_profile": "https://wordpress.stackexchange.com/users/106821",
"pm_score": 4,
"selected": false,
"text": "<pre><code>add_action('woocommerce_after_single_product_summary', 'show_cross_sell_in_single_product', 30);\nfunction show_cross_sell_in_single_product(){\n $crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true);\n\n if(empty($crosssells)){\n return;\n }\n\n $args = array( \n 'post_type' => 'product', \n 'posts_per_page' => -1, \n 'post__in' => $crosssells \n );\n $products = new WP_Query( $args );\n if( $products->have_posts() ) : \n echo '<div class=\"cross-sells\"><h2>Cross-Sells Products</h2>';\n woocommerce_product_loop_start();\n while ( $products->have_posts() ) : $products->the_post();\n wc_get_template_part( 'content', 'product' );\n endwhile; // end of the loop.\n woocommerce_product_loop_end();\n echo '</div>';\n endif;\n wp_reset_postdata();\n}\n</code></pre>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122104/"
]
| I am trying to show cross sells on a single product page rather than in the cart:
So far I've tried the following code:
```
<?php do_action( 'woocommerce_after_single_product_summary_data_tabs' ); ?>
<?php if ( $product->get_upsell_ids() ) : ?>
<div class="single_product_summary_upsell">
<?php do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
</div><!-- .single_product_summary_upsells -->
<?php endif; ?>
<?php if ( $product->get_cross_sell_ids() ) : ?>
<div class="single_product_summary_upsell">
<?php do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
</div><!-- .single_product_summary_upsells -->
<?php endif; ?>
<div class="single_product_summary_related">
<?php do_action( 'woocommerce_after_single_product_summary_related_products' ); ?>
</div><!-- .single_product_summary_related -->
</div><!-- .columns -->
```
However this will only show upsells below upsells, so it's just the same content twice. I am not sure on what action to use instead of
```
do_action( 'woocommerce_after_single_product_summary_upsell_display' ); ?>
``` | ```
add_action('woocommerce_after_single_product_summary', 'show_cross_sell_in_single_product', 30);
function show_cross_sell_in_single_product(){
$crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true);
if(empty($crosssells)){
return;
}
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post__in' => $crosssells
);
$products = new WP_Query( $args );
if( $products->have_posts() ) :
echo '<div class="cross-sells"><h2>Cross-Sells Products</h2>';
woocommerce_product_loop_start();
while ( $products->have_posts() ) : $products->the_post();
wc_get_template_part( 'content', 'product' );
endwhile; // end of the loop.
woocommerce_product_loop_end();
echo '</div>';
endif;
wp_reset_postdata();
}
``` |
270,985 | <p>If I update WordPress my custom data will be deleted from the wp_users table? I add new custom field and store data to users at this field if I update WordPress and WordPress needs to update this table my custom field will be deleted?</p>
| [
{
"answer_id": 270987,
"author": "Ruturaj",
"author_id": 43266,
"author_profile": "https://wordpress.stackexchange.com/users/43266",
"pm_score": 0,
"selected": false,
"text": "<p>No, your Custom User Data (i.e. User Meta) will remain safe in database even after you update your WordPress. I've not seen so far the WordPress Updater touching/altering the data in any of the tables.</p>\n\n<p>(Just to keep posted, it's the <code>[prefix]_usermeta</code> table that holds the user related data; not the <code>[prefix]_users</code> table.</p>\n"
},
{
"answer_id": 270991,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>It is possible, especially if the update includes changes to the user table. The only way to be sure is to test it, but for future reference:</p>\n\n<p><strong>Never modify the scheme of WordPress Tables</strong></p>\n\n<p>If you need to add additional information about something, WordPress provides meta, user meta, site meta, post meta, comment meta. You may know these as custom fields.</p>\n\n<p>For example:</p>\n\n<pre><code>$value = get_user_meta( $user_id, 'example', true );\nupdate_user_meta( $user_id, 'example', 'newvalue' );\n$all_meta = get_user_meta( $user_id );\n</code></pre>\n\n<p>Adding columns manually to tables also bypasses the caching layer slowing things down, encourages writing manual SQL statements ( you could have used the <code>WP_User_Query</code> class! ), and stops the information being imported/exported ( custom post types get put in content exports, custom tables don't )</p>\n\n<p>I recommend writing a small WP CLI command to fetch each user and store these columns as user meta instead</p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/270985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117356/"
]
| If I update WordPress my custom data will be deleted from the wp\_users table? I add new custom field and store data to users at this field if I update WordPress and WordPress needs to update this table my custom field will be deleted? | It is possible, especially if the update includes changes to the user table. The only way to be sure is to test it, but for future reference:
**Never modify the scheme of WordPress Tables**
If you need to add additional information about something, WordPress provides meta, user meta, site meta, post meta, comment meta. You may know these as custom fields.
For example:
```
$value = get_user_meta( $user_id, 'example', true );
update_user_meta( $user_id, 'example', 'newvalue' );
$all_meta = get_user_meta( $user_id );
```
Adding columns manually to tables also bypasses the caching layer slowing things down, encourages writing manual SQL statements ( you could have used the `WP_User_Query` class! ), and stops the information being imported/exported ( custom post types get put in content exports, custom tables don't )
I recommend writing a small WP CLI command to fetch each user and store these columns as user meta instead |
271,032 | <p>it is very difficult to find an online article, or even in the WP codex, to create a section inside a section for the theme options. the below screenshot shows what i am trying to create:
<a href="https://i.stack.imgur.com/ZA2xi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZA2xi.png" alt="enter image description here"></a></p>
<p>i have the simple code below creating such, but i am not sure how to create a section inside a section. any help would be greatly appreciated, and help a future developer. </p>
<pre><code>function site_customize_register( $wp_customize ) {
/**
* section
*/
//so called "parent" section
$wp_customize->add_section("homepage_options",[
"title" => __("Homepage Options", "customizer_homepage_options_section"),
"priority" => 10,
]);
//so called "parent" section
$wp_customize->add_section("homepage_options_donate_now",[
"title" => __("Donate Now", "customizer_homepage_options_section"),
"priority" => 10,
]);
/**
* setting
*/
$wp_customize->add_setting("four_image_cta_block", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_two", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_three", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_four", [
"default" => "",
"transport" => "postMessage",
]);
/**
* control
*/
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block",
[
"label" => __("First Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_two",
[
"label" => __("Second Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_two",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_three",
[
"label" => __("Third Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_three",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_four",
[
"label" => __("Fourth Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_four",
"type" => "textarea",
]
));
}
</code></pre>
| [
{
"answer_id": 270987,
"author": "Ruturaj",
"author_id": 43266,
"author_profile": "https://wordpress.stackexchange.com/users/43266",
"pm_score": 0,
"selected": false,
"text": "<p>No, your Custom User Data (i.e. User Meta) will remain safe in database even after you update your WordPress. I've not seen so far the WordPress Updater touching/altering the data in any of the tables.</p>\n\n<p>(Just to keep posted, it's the <code>[prefix]_usermeta</code> table that holds the user related data; not the <code>[prefix]_users</code> table.</p>\n"
},
{
"answer_id": 270991,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>It is possible, especially if the update includes changes to the user table. The only way to be sure is to test it, but for future reference:</p>\n\n<p><strong>Never modify the scheme of WordPress Tables</strong></p>\n\n<p>If you need to add additional information about something, WordPress provides meta, user meta, site meta, post meta, comment meta. You may know these as custom fields.</p>\n\n<p>For example:</p>\n\n<pre><code>$value = get_user_meta( $user_id, 'example', true );\nupdate_user_meta( $user_id, 'example', 'newvalue' );\n$all_meta = get_user_meta( $user_id );\n</code></pre>\n\n<p>Adding columns manually to tables also bypasses the caching layer slowing things down, encourages writing manual SQL statements ( you could have used the <code>WP_User_Query</code> class! ), and stops the information being imported/exported ( custom post types get put in content exports, custom tables don't )</p>\n\n<p>I recommend writing a small WP CLI command to fetch each user and store these columns as user meta instead</p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/271032",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1354/"
]
| it is very difficult to find an online article, or even in the WP codex, to create a section inside a section for the theme options. the below screenshot shows what i am trying to create:
[](https://i.stack.imgur.com/ZA2xi.png)
i have the simple code below creating such, but i am not sure how to create a section inside a section. any help would be greatly appreciated, and help a future developer.
```
function site_customize_register( $wp_customize ) {
/**
* section
*/
//so called "parent" section
$wp_customize->add_section("homepage_options",[
"title" => __("Homepage Options", "customizer_homepage_options_section"),
"priority" => 10,
]);
//so called "parent" section
$wp_customize->add_section("homepage_options_donate_now",[
"title" => __("Donate Now", "customizer_homepage_options_section"),
"priority" => 10,
]);
/**
* setting
*/
$wp_customize->add_setting("four_image_cta_block", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_two", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_three", [
"default" => "",
"transport" => "postMessage",
]);
$wp_customize->add_setting("four_image_cta_block_four", [
"default" => "",
"transport" => "postMessage",
]);
/**
* control
*/
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block",
[
"label" => __("First Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_two",
[
"label" => __("Second Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_two",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_three",
[
"label" => __("Third Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_three",
"type" => "textarea",
]
));
$wp_customize->add_control(new WP_Customize_Control(
$wp_customize,
"four_image_cta_block_four",
[
"label" => __("Fourth Item Link Text", "customizer_four_image_cta_block_label"),
"section" => "homepage_options",
"settings" => "four_image_cta_block_four",
"type" => "textarea",
]
));
}
``` | It is possible, especially if the update includes changes to the user table. The only way to be sure is to test it, but for future reference:
**Never modify the scheme of WordPress Tables**
If you need to add additional information about something, WordPress provides meta, user meta, site meta, post meta, comment meta. You may know these as custom fields.
For example:
```
$value = get_user_meta( $user_id, 'example', true );
update_user_meta( $user_id, 'example', 'newvalue' );
$all_meta = get_user_meta( $user_id );
```
Adding columns manually to tables also bypasses the caching layer slowing things down, encourages writing manual SQL statements ( you could have used the `WP_User_Query` class! ), and stops the information being imported/exported ( custom post types get put in content exports, custom tables don't )
I recommend writing a small WP CLI command to fetch each user and store these columns as user meta instead |
271,034 | <p>Hello I have a small issue regarding my linking in my style.css</p>
<p>For example:</p>
<pre><code>@font-face {
src: url('wp-content/themes/mytheme/fonts/font.ttf');
}
</code></pre>
<p>and</p>
<pre><code>.div {
background: url('wp-content/themes/mytheme/images/img.png');
}
</code></pre>
<p>My home page works perfectly, assets link correctly but when I go to another page such as "about" the links are broken because it does this:</p>
<p><code>www.url.com/about/wp-content/themes/mytheme/images/img.png</code></p>
<p>Anyone know why this is happening?</p>
<p>Thanks</p>
| [
{
"answer_id": 271037,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 2,
"selected": false,
"text": "<p>For the following structure:</p>\n\n<pre><code>/wp-content/\n /themes/\n /mytheme/\n style.css\n /images/\n img.png\n /font/\n font.tff \n</code></pre>\n\n<p>reference <code>img.png</code> and <code>font.tff</code> like so:</p>\n\n<pre><code>.div {\n background-image: url('images/img.png');\n}\n\n@font-face {\n src: url('fonts/font.ttf');\n}\n</code></pre>\n\n<p>For when css files are in a directory:</p>\n\n<pre><code>/wp-content/\n /themes/\n /mytheme/\n /css/\n some.css\n /images/\n img.png\n /font/\n font.tff \n</code></pre>\n\n<p>In some.css you would reference them like so:</p>\n\n<pre><code>.div {\n background-image: url('../images/img.png');\n}\n</code></pre>\n"
},
{
"answer_id": 271038,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": true,
"text": "<p>You're using relative URLs that will always look inside the current URL structure. You either need to add a slash before wp-content, or put in the full URL to the resources.</p>\n\n<p>So for example: <code>src: url('/wp-content/themes/mytheme/fonts/font.ttf');</code></p>\n\n<p>or <code>src: url('http://example.com/wp-content/themes/mytheme/fonts/font.ttf');</code></p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/271034",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112836/"
]
| Hello I have a small issue regarding my linking in my style.css
For example:
```
@font-face {
src: url('wp-content/themes/mytheme/fonts/font.ttf');
}
```
and
```
.div {
background: url('wp-content/themes/mytheme/images/img.png');
}
```
My home page works perfectly, assets link correctly but when I go to another page such as "about" the links are broken because it does this:
`www.url.com/about/wp-content/themes/mytheme/images/img.png`
Anyone know why this is happening?
Thanks | You're using relative URLs that will always look inside the current URL structure. You either need to add a slash before wp-content, or put in the full URL to the resources.
So for example: `src: url('/wp-content/themes/mytheme/fonts/font.ttf');`
or `src: url('http://example.com/wp-content/themes/mytheme/fonts/font.ttf');` |
271,046 | <p>I'm using the Twenty Seventeen theme and would like to add an image and some links to the left part under the page title. I searched all over the web, but couldn't find a good solution. Is there any way to accomplish that without creating a custom static page?</p>
<p><a href="https://i.stack.imgur.com/iSxMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iSxMG.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 271720,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 0,
"selected": false,
"text": "<p>I suppose that the most obvious way is javascript which will be used after the page loaded. By the way WP has included jQuery, so you can:</p>\n\n<ol>\n<li>create styles to achieve a clear two columns design (or use already existing ones if you are using bootstrap-like stylesheets, I'll assume forward that your WP uses it)</li>\n<li>find the block of html you want to shift left and assign <code>.column</code> class to it.</li>\n<li>It's possible that you will have to wrap both of you columns into a block similar to one with a bootstrap class <code>.row</code>.</li>\n<li>Create with jQuery a new element with your image and other content that should be displayed.</li>\n<li>Insert the element from the point 3 to the DOM (existing HTML structure of your page) right after opened block <code>.row</code> from the point 2.</li>\n</ol>\n\n<p>That's it.\nFeel free to ask details on topic.</p>\n"
},
{
"answer_id": 271724,
"author": "Andrii Shekhirev",
"author_id": 122807,
"author_profile": "https://wordpress.stackexchange.com/users/122807",
"pm_score": 2,
"selected": true,
"text": "<p>There doesn't seem to be any specific function to hook to, so a back-end solution would require altering the \"/template-parts/page/content-page.php template file (via a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a>, preferably), namely adding your desired elements right before the closing <code></header></code> tag, for example:</p>\n\n<pre><code><header class=\"entry-header\">\n <?php the_title( '<h1 class=\"entry-title\">', '</h1>' ); ?>\n <?php twentyseventeen_edit_link( get_the_ID() ); ?>\n <!-- START new code -->\n <img src=\"http://image-source.jpg\">\n <span class=\"left-text\">Insert your text here</span>\n <!-- END new code -->\n</header><!-- .entry-header -->\n</code></pre>\n\n<p>You can also add conditional statements if you wish the new content to be displayed on a specific page/pages, e.g. for a front page:</p>\n\n<pre><code><!-- START new code -->\n<?php if ( is_front_page() ) { ?>\n <img src=\"http://image-source.jpg\">\n <span class=\"left-text\">Insert your text here</span>\n<?php } ?>\n<!-- END new code -->\n</code></pre>\n\n<p>for a specific page ID:</p>\n\n<pre><code><!-- START new code -->\n<?php if ( 25 == get_the_ID() ) { ?>\n <img src=\"http://image-source.jpg\">\n <span class=\"left-text\">Insert your text here</span>\n<?php } ?>\n<!-- END new code -->\n</code></pre>\n"
},
{
"answer_id": 271805,
"author": "Jevuska",
"author_id": 18731,
"author_profile": "https://wordpress.stackexchange.com/users/18731",
"pm_score": 1,
"selected": false,
"text": "<p>If it is related to <code>the_title</code>, you can use filter <a href=\"https://developer.wordpress.org/reference/functions/get_the_title/\" rel=\"nofollow noreferrer\" title=\"apply_filters( 'the_title', $title, $id )\"><code>the_title</code></a>, but base on twenty seventeen theme code for page template, your custom code will be markup inside <code>h1</code> element <a href=\"https://themes.trac.wordpress.org/browser/twentyseventeen/1.3/template-parts/page/content-page.php#L17\" rel=\"nofollow noreferrer\"><code>the_title( '<h1 class=\"entry-title\">', '</h1>' );</code></a></p>\n\n<p>For example code, just say we need to add only in page with the post id = 2</p>\n\n<pre><code>add_filter( 'the_title', function( $title, $id ) {\n static $i;\n\n //add conditional page and in loop, i.e post id = 2\n if ( is_page( 2 ) && in_the_loop() ) {\n $i++;\n\n //add conditional for filter position\n if ( 1 === $i ) {\n\n //add your code here\n $title .= '<p><img src=\"image.jpg\"></p>';\n $title .= '<p>' . __( 'Text', 'textdomain' ) . '</p>';\n $title .= '<p><a href=\"#link\">' . __( 'Link' ) . '</a></p>';\n }\n }\n\n return $title;\n}, 10, 2 );\n</code></pre>\n\n<p>Just change the conditional statement to make it work in another posts or pages.</p>\n"
}
]
| 2017/06/22 | [
"https://wordpress.stackexchange.com/questions/271046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122418/"
]
| I'm using the Twenty Seventeen theme and would like to add an image and some links to the left part under the page title. I searched all over the web, but couldn't find a good solution. Is there any way to accomplish that without creating a custom static page?
[](https://i.stack.imgur.com/iSxMG.png) | There doesn't seem to be any specific function to hook to, so a back-end solution would require altering the "/template-parts/page/content-page.php template file (via a [child theme](https://codex.wordpress.org/Child_Themes), preferably), namely adding your desired elements right before the closing `</header>` tag, for example:
```
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php twentyseventeen_edit_link( get_the_ID() ); ?>
<!-- START new code -->
<img src="http://image-source.jpg">
<span class="left-text">Insert your text here</span>
<!-- END new code -->
</header><!-- .entry-header -->
```
You can also add conditional statements if you wish the new content to be displayed on a specific page/pages, e.g. for a front page:
```
<!-- START new code -->
<?php if ( is_front_page() ) { ?>
<img src="http://image-source.jpg">
<span class="left-text">Insert your text here</span>
<?php } ?>
<!-- END new code -->
```
for a specific page ID:
```
<!-- START new code -->
<?php if ( 25 == get_the_ID() ) { ?>
<img src="http://image-source.jpg">
<span class="left-text">Insert your text here</span>
<?php } ?>
<!-- END new code -->
``` |
271,076 | <h1>What I want to accomplish</h1>
<p>I need an aside to pull the last 5 posts from a specific set of 5 categories. </p>
<p>Not the latest of each, not the last 5 of each, but the last 5 total posts from the 5 categories.</p>
<p>The category IDs are: 89,90,91,92,93</p>
<h1>Background</h1>
<p>I have 5 different category pages, so this has been making it trickier. Each of these uses an include for the aside. I am writing that logic in that include. </p>
<h2>PHP</h2>
<pre><code><?php
if ( in_category( 92, $post_id ) ) : ?>
$bfaCat = 'bfa-cat-ba';
<?php endif; ?>
</code></pre>
<p>Then I have to loop through. Not applying anything if the post is not in any of the categories. But if the posts are of that category then add a variable (as <code>$bfaCat</code>) with the following class (on right) applied if it has the following category id (on left)</p>
<pre><code>89 - bfa-cat-bl
90 - bfa-cat-fs
91 - bfa-cat-s1
92 - bfa-cat-ba
93 - bfa-cat-ea
</code></pre>
<h2>HTML - ATTEMPT 1 - in template</h2>
<pre><code><div class="bfa-category <?=$bfaCat;?>">
<?php the_category(); ?>
</div>
</code></pre>
<h2>HTML - desired output example</h2>
<pre><code><div class="bfa-category bfa-cat-bl">
<?php the_category(); ?>
</div>
</code></pre>
<h2>HTML - ATTEMPT 2 - Would this be better if modified?</h2>
<p>I know this is sloppy but I also tried it inline but it just applied this class to everything</p>
<pre><code><div class="bfa-category <?php if (get_category('91')) echo 'bfa-cat-s1'; ?>">
<?php the_category(); ?>
</div>
</code></pre>
<p>So it seems like the class is being echoed into everything. </p>
| [
{
"answer_id": 271088,
"author": "WizardCoder",
"author_id": 121085,
"author_profile": "https://wordpress.stackexchange.com/users/121085",
"pm_score": 1,
"selected": false,
"text": "<p><code>get_category('91')</code> is always going to return an object of category ID 91's data. This means your if statement is always going to return as true. You need to get the current iterated posts assigned category ID and then check if it is 91.</p>\n\n<pre><code><!-- Return objects of current iterated posts associated categories -->\n$categories = get_the_category();\n<!-- Get current iterated posts assigned category ID from $categories object. The [0] is because a post can be assigned to multiple categories. \nIn your example you are probably only assigning one category per post, so you just need to grab the ID of the first category in the returned object. -->\n$category_id = $categories[0]->cat_ID;\n<!-- Check if current iterated assigned posts category ID is equal to 91 -->\n<div class=\"bfa-category <?php if ($category_id == 91) echo 'bfa-cat-s1'; ?>\">\n <?php the_category(); ?>\n</div>\n</code></pre>\n"
},
{
"answer_id": 271152,
"author": "JGallardo",
"author_id": 104295,
"author_profile": "https://wordpress.stackexchange.com/users/104295",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I ended up coding based on help. I used the PHP suggested to get assign the category.\n cat_ID;\n ?></p>\n\n<p>Then below it I put that above the actual element where I created the logic to assign the appropriate class</p>\n\n<h2>PHP</h2>\n\n<pre><code><div class=\"bfa-category \n <?php \n if ($category_id == 89) {\n echo 'bfa-cat-bl';\n } elseif ($category_id == 90) {\n echo 'bfa-cat-fs';\n } elseif ($category_id == 91) {\n echo 'bfa-cat-s1';\n } elseif ($category_id == 92) {\n echo 'bfa-cat-ba';\n } elseif ($category_id == 93) {\n echo 'bfa-cat-ea';\n }\n ?>\">\n <?php the_category(); ?>\n</div>\n</code></pre>\n"
}
]
| 2017/06/23 | [
"https://wordpress.stackexchange.com/questions/271076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104295/"
]
| What I want to accomplish
=========================
I need an aside to pull the last 5 posts from a specific set of 5 categories.
Not the latest of each, not the last 5 of each, but the last 5 total posts from the 5 categories.
The category IDs are: 89,90,91,92,93
Background
==========
I have 5 different category pages, so this has been making it trickier. Each of these uses an include for the aside. I am writing that logic in that include.
PHP
---
```
<?php
if ( in_category( 92, $post_id ) ) : ?>
$bfaCat = 'bfa-cat-ba';
<?php endif; ?>
```
Then I have to loop through. Not applying anything if the post is not in any of the categories. But if the posts are of that category then add a variable (as `$bfaCat`) with the following class (on right) applied if it has the following category id (on left)
```
89 - bfa-cat-bl
90 - bfa-cat-fs
91 - bfa-cat-s1
92 - bfa-cat-ba
93 - bfa-cat-ea
```
HTML - ATTEMPT 1 - in template
------------------------------
```
<div class="bfa-category <?=$bfaCat;?>">
<?php the_category(); ?>
</div>
```
HTML - desired output example
-----------------------------
```
<div class="bfa-category bfa-cat-bl">
<?php the_category(); ?>
</div>
```
HTML - ATTEMPT 2 - Would this be better if modified?
----------------------------------------------------
I know this is sloppy but I also tried it inline but it just applied this class to everything
```
<div class="bfa-category <?php if (get_category('91')) echo 'bfa-cat-s1'; ?>">
<?php the_category(); ?>
</div>
```
So it seems like the class is being echoed into everything. | `get_category('91')` is always going to return an object of category ID 91's data. This means your if statement is always going to return as true. You need to get the current iterated posts assigned category ID and then check if it is 91.
```
<!-- Return objects of current iterated posts associated categories -->
$categories = get_the_category();
<!-- Get current iterated posts assigned category ID from $categories object. The [0] is because a post can be assigned to multiple categories.
In your example you are probably only assigning one category per post, so you just need to grab the ID of the first category in the returned object. -->
$category_id = $categories[0]->cat_ID;
<!-- Check if current iterated assigned posts category ID is equal to 91 -->
<div class="bfa-category <?php if ($category_id == 91) echo 'bfa-cat-s1'; ?>">
<?php the_category(); ?>
</div>
``` |
271,096 | <p>What is the best way to modify the <code><header></code> element on all pages? I need to edit the <code><header></code> element on every page from:</p>
<pre><code><header class="light">
</code></pre>
<p>To </p>
<pre><code><header class="light" itemscope="itemscope" itemtype="http://schema.org/WPHeader">
</code></pre>
<p>and I would like it to read Is there a way to do this via a custom function? I know I can directly edit <code>my header.php</code> file, but I'd like to avoid that. </p>
<p>Perhaps there a WordPress filter hook that can modify the element for each page of my site? I looked through the <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference" rel="nofollow noreferrer">WP list of filter hooks</a>, but didn't see anything that would be relevant in this case. I may have missed it though.</p>
<p>The objective of this task is to add schema data, in microdata format, to my site (per the instructions on <a href="http://iurianu.info/articles/schema-org/add-schema-org-markup-wordpress-site/" rel="nofollow noreferrer">this page</a>). If there is an easier/better method I would be interested in hearing about it. In the past I've added schema data, in JSON format, using Google Tag Manager. But in that case I had a JSON-LD file already prepared for me. In this particular case I can't figure out how to prepare that file.</p>
| [
{
"answer_id": 271101,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure that that kind of filter is available in wordpress. But, you could do it though javascript. And moreover, if you would like to make condition check for specific data. you could run in functions.php file.</p>\n\n<pre><code>function schema_filter() {\n\n//write your condition in here and pass variable to javascript with php code like that\n\n ?>\n <script>\n\n jQuery(document).ready(function($){\n $('header').attr('itemscope', 'itemscope');\n $('header').attr('itemtype', 'http://schema.org/WPHeader');\n });\n\n </script>\n <?php\n}\nadd_action('wp_footer', 'schema_filter');\n</code></pre>\n"
},
{
"answer_id": 271107,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The <code><header></code> elements are usually echoed directly by the theme. So without any hook or filter to change them. In that case, there is no way to change those elements with a function. Check your theme.</p>\n\n<p>You could, of course, use javascript to place you attributes, but that would happen on the user end. Search engines would not see it. Since schema.org attributes are meant for search engines that is pretty useless.</p>\n\n<p>What you could try is <a href=\"http://php.net/manual/en/ref.outcontrol.php\" rel=\"nofollow noreferrer\">buffering the whole page</a> and do a search and replace right before the page is completed. This is likely to run you into serious difficulties, but theoretically it's possible.</p>\n\n<p>So, your best course of action is build a child theme and replace the part where the <code><header></code> tags are generated with your version. You would have to make a child theme anyway if you were going into the direction of a custom function as you suggest.</p>\n"
}
]
| 2017/06/23 | [
"https://wordpress.stackexchange.com/questions/271096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51204/"
]
| What is the best way to modify the `<header>` element on all pages? I need to edit the `<header>` element on every page from:
```
<header class="light">
```
To
```
<header class="light" itemscope="itemscope" itemtype="http://schema.org/WPHeader">
```
and I would like it to read Is there a way to do this via a custom function? I know I can directly edit `my header.php` file, but I'd like to avoid that.
Perhaps there a WordPress filter hook that can modify the element for each page of my site? I looked through the [WP list of filter hooks](https://codex.wordpress.org/Plugin_API/Filter_Reference), but didn't see anything that would be relevant in this case. I may have missed it though.
The objective of this task is to add schema data, in microdata format, to my site (per the instructions on [this page](http://iurianu.info/articles/schema-org/add-schema-org-markup-wordpress-site/)). If there is an easier/better method I would be interested in hearing about it. In the past I've added schema data, in JSON format, using Google Tag Manager. But in that case I had a JSON-LD file already prepared for me. In this particular case I can't figure out how to prepare that file. | The `<header>` elements are usually echoed directly by the theme. So without any hook or filter to change them. In that case, there is no way to change those elements with a function. Check your theme.
You could, of course, use javascript to place you attributes, but that would happen on the user end. Search engines would not see it. Since schema.org attributes are meant for search engines that is pretty useless.
What you could try is [buffering the whole page](http://php.net/manual/en/ref.outcontrol.php) and do a search and replace right before the page is completed. This is likely to run you into serious difficulties, but theoretically it's possible.
So, your best course of action is build a child theme and replace the part where the `<header>` tags are generated with your version. You would have to make a child theme anyway if you were going into the direction of a custom function as you suggest. |
271,193 | <p>I know how to use shortcodes, even making them but what I need to understand is that a shortcode is a plain text stored in database as a post content, So how a plain text like this can be converted into dynamic.</p>
<p>What I want to know is how an <code>x</code> text can be handled before the server send it to the browser to behave deffirently?</p>
| [
{
"answer_id": 271194,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 5,
"selected": true,
"text": "<p>When using <code>the_content()</code>, WordPress will run several filters to process the text coming from the editor. These filters process the content before it is sent to the browser. <code>do_shortcode</code> is the filter that handles shortcodes. </p>\n\n<p>From <code>/wp-includes/default-filters.php</code>:</p>\n\n<pre><code>// Shortcodes\nadd_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop()\n</code></pre>\n\n<p><code>do_shortcode()</code> is used to search content for shortcodes and filter the shortcodes through their hooks. </p>\n\n<p>You can apply the <code>do_shortcode</code> filter to any string. For example, if you have a meta box with a text area and you would like to allow users to enter shortcodes in the text area, you could wire up the <code>do_shortcode</code> filter to handle that.</p>\n\n<p><strong>A shortcode example:</strong></p>\n\n<pre><code>[my-shortcode param1=something param2=value]Text...[/my-shortcode]\n</code></pre>\n\n<p>When WordPress finds this shortcode in the content, it will run the function associated with the shortcode tag <code>my-shortcode</code>. </p>\n\n<pre><code>/**\n * An example shortcode.\n *\n * @param array $atts\n * @param string $content\n * @param string $tag Shortcode tag\n * @return string\n */\nadd_shortcode( 'my-shortcode', 'wpse_example_shortcode' );\nfunction wpse_example_shortcode( $atts, $content = '', $tag ) {\n $a = shortcode_atts( [\n 'param1' => false,\n 'param2' => false,\n ], $atts );\n\n // code...\n\n return $content . '!!!';\n}\n</code></pre>\n\n<p>In this case, WordPress will run the function <code>wpse_example_shortcode()</code> passing <code>$atts</code> (parameters and their values, e.g. param1, param2), <code>$content</code> (<em>Text...</em>), and <code>$tag</code> (the shortcode tag used, <code>my-shortcode</code>).</p>\n\n<p>Valid shortcodes (including their parameters and content) will be replaced with the output of the callback function that they are associated with. Invalid shortcodes will be output just as they were entered in the back end.</p>\n"
},
{
"answer_id": 271196,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a little note:</p>\n\n<p>The shortcode's API evolves around <a href=\"http://php.net/preg_replace_callback\" rel=\"nofollow noreferrer\"><code>preg_replace_callback</code></a> where we define the custom callbacks with our shortcode definitions.</p>\n\n<p>The shortcodes in the text are parsed with a complex regular expression pattern that you can check out in the <a href=\"https://developer.wordpress.org/reference/functions/get_shortcode_regex/\" rel=\"nofollow noreferrer\"><code>get_shortcode_regex()</code></a>. </p>\n\n<p>The implementation of this in the core gets more complicated as we lay out the details ;-)</p>\n"
}
]
| 2017/06/24 | [
"https://wordpress.stackexchange.com/questions/271193",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102224/"
]
| I know how to use shortcodes, even making them but what I need to understand is that a shortcode is a plain text stored in database as a post content, So how a plain text like this can be converted into dynamic.
What I want to know is how an `x` text can be handled before the server send it to the browser to behave deffirently? | When using `the_content()`, WordPress will run several filters to process the text coming from the editor. These filters process the content before it is sent to the browser. `do_shortcode` is the filter that handles shortcodes.
From `/wp-includes/default-filters.php`:
```
// Shortcodes
add_filter( 'the_content', 'do_shortcode', 11 ); // AFTER wpautop()
```
`do_shortcode()` is used to search content for shortcodes and filter the shortcodes through their hooks.
You can apply the `do_shortcode` filter to any string. For example, if you have a meta box with a text area and you would like to allow users to enter shortcodes in the text area, you could wire up the `do_shortcode` filter to handle that.
**A shortcode example:**
```
[my-shortcode param1=something param2=value]Text...[/my-shortcode]
```
When WordPress finds this shortcode in the content, it will run the function associated with the shortcode tag `my-shortcode`.
```
/**
* An example shortcode.
*
* @param array $atts
* @param string $content
* @param string $tag Shortcode tag
* @return string
*/
add_shortcode( 'my-shortcode', 'wpse_example_shortcode' );
function wpse_example_shortcode( $atts, $content = '', $tag ) {
$a = shortcode_atts( [
'param1' => false,
'param2' => false,
], $atts );
// code...
return $content . '!!!';
}
```
In this case, WordPress will run the function `wpse_example_shortcode()` passing `$atts` (parameters and their values, e.g. param1, param2), `$content` (*Text...*), and `$tag` (the shortcode tag used, `my-shortcode`).
Valid shortcodes (including their parameters and content) will be replaced with the output of the callback function that they are associated with. Invalid shortcodes will be output just as they were entered in the back end. |
271,195 | <p>I have a <a href="https://developer.wordpress.org/reference/functions/add_image_size/" rel="nofollow noreferrer">custom image size</a> <code>hello-image</code>:</p>
<pre><code>add_image_size( 'hello-image', 700, 300, true );
</code></pre>
<p>Whenever an image is uploaded, I compress the cropped <code>hello-image</code> sized image to <code>40%</code> JPEG compression. It works great in all cases except...</p>
<h2>The problem</h2>
<p>If the <strong>width</strong> of the original image is <em>greater</em> than <code>700px</code> it works just fine. But if the width of it is <em>less</em> than <code>700px</code>, the compression goes to around <code>0%</code>.</p>
<h2>How to test it</h2>
<p>Download the following two images:</p>
<p><a href="https://i.imgur.com/4QJjEMW.jpg" rel="nofollow noreferrer">BIG: 784px × 441px</a></p>
<p><a href="https://i.imgur.com/J9SOdQe.jpg" rel="nofollow noreferrer">SMALL: 670px × 377px</a></p>
<p>Then I have created a plugin which has all the relevant code:</p>
<pre><code><?php
/*
Plugin Name: WPSE: custom image size and JPEG compression
Description: custom image size and JPEG compression
Author: WPSE
Version: 1.0
*/
// Set JPEG compression quality
add_filter('jpeg_quality', create_function('$quality', 'return 100;'));
add_action('added_post_meta', 'ad_update_jpeg_quality', 10, 4);
function ad_update_jpeg_quality($meta_id, $attach_id, $meta_key, $attach_meta) {
if ($meta_key == '_wp_attachment_metadata') {
$post = get_post($attach_id);
if ($post->post_mime_type == 'image/jpeg' && is_array($attach_meta['sizes'])) {
$pathinfo = pathinfo($attach_meta['file']);
$uploads = wp_upload_dir();
$dir = $uploads['basedir'] . '/' . $pathinfo['dirname'];
foreach ($attach_meta['sizes'] as $size => $value) {
$image = $dir . '/' . $value['file'];
$resource = imagecreatefromjpeg($image);
if ($size == 'large') {
// set the jpeg quality for 'large' size
imagejpeg($resource, $image, 35);
} elseif ($size == 'medium') {
// set the jpeg quality for the 'medium' size
imagejpeg($resource, $image, 35);
} elseif ($size == 'hello-image') {
// set the jpeg quality for the 'hello-image' size
imagejpeg($resource, $image, 40);
} else {
// set the jpeg quality for the rest of sizes
imagejpeg($resource, $image, 35); // 38
}
imagedestroy($resource);
}
}
}
}
// add custom image sizes to media uploader
function my_insert_custom_image_sizes( $sizes ) {
// get the custom image sizes
global $_wp_additional_image_sizes;
// if there are none, just return the built-in sizes
if ( empty( $_wp_additional_image_sizes ) )
return $sizes;
// add all the custom sizes to the built-in sizes
foreach ( $_wp_additional_image_sizes as $id => $data ) {
// take the size ID (e.g., 'my-name'), replace hyphens with spaces,
// and capitalise the first letter of each word
if ( !isset($sizes[$id]) )
$sizes[$id] = ucfirst( str_replace( '-', ' ', $id ) );
}
return $sizes;
}
// Which custom image size selected by default
function my_set_default_image_size () {
return 'hello-image';
}
function custom_image_setup () {
// custom image sizes
add_image_size( 'medium', 300, 9999 ); // medium
add_image_size( 'hello-image', 700, 300, true ); // custom
add_image_size( 'large', 700, 3000 ); // large
add_filter( 'image_size_names_choose', 'my_insert_custom_image_sizes' );
add_filter( 'pre_option_image_default_size', 'my_set_default_image_size' );
}
add_action( 'after_setup_theme', 'custom_image_setup' );
</code></pre>
<p>Now, upload the <em>big</em> image and see how the <code>hello-image</code> image is compressed fine. Then upload the <em>small</em> image and see how the same image size is compressed terribly. So to clarify, this is the results:</p>
<pre><code>700x300 = 40% compression
670x300 = 0% compression
</code></pre>
<p>Both of which are generated via the exact same custom image size. What is the cause of this and how can it be fixed? </p>
<p>I should highlight that my colleague posted a <a href="https://wordpress.stackexchange.com/questions/271192/add-image-size-cropped-only-if-width-of-the-image-matches-or-is-higher">question here</a> asking how to avoid creating this image size if the width is lower than <code>700px</code>... but I'm a WordPress geek who would rather resolve the cause of the problem than add a hacky fix to it.</p>
<p>Finally, I started seeing this problem in a recent WordPress update, so it may be a bug in core, as opposed to an issue in my code.</p>
<p><strong>Edit</strong>: Read the <a href="https://wordpress.stackexchange.com/questions/271195/setting-jpeg-compression-for-custom-image-sizes-doesnt-work-in-specific-cases#comment402886_271261">update</a>.</p>
| [
{
"answer_id": 271198,
"author": "berend",
"author_id": 120717,
"author_profile": "https://wordpress.stackexchange.com/users/120717",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting, I tried it and the small image gets displayed 670x300 and the big image 700x300. Seems to me like its is doing exactly what it needs to do, it crops the image if either the height or width are above the image type (or both). </p>\n\n<p>I understand you only want to crop the image if the height is higher? Then using this would work:</p>\n\n<pre><code> add_image_size( 'hello-world', 700, 0, true );\n</code></pre>\n\n<p>I re-upload the images after that and the small images gets displayed 670 by 377 and the big image 700 by 394. I uploaded another smaller version (516x290) and it does not get cropped at all.</p>\n\n<p>Although when you upload an image like 690x4000 it also does not get cropped.</p>\n"
},
{
"answer_id": 271261,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p><em>Some suggestions:</em></p>\n\n<p>If you want to try out the <em>Image Editor API</em> you can try to replace</p>\n\n<pre><code>imagejpeg( $resource, $image, 35 );\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>$editor = wp_get_image_editor( $image ); \nif ( ! is_wp_error( $editor ) )\n{\n $editor->set_quality( 35 );\n $editor->save( $image );\n}\nunset( $editor );\n</code></pre>\n\n<p>Also try to test e.g. these parts:</p>\n\n<pre><code>$resource = imagecreatefromjpeg( $image );\nif( false !== $resource )\n{\n imagejpeg( $resource, $image, 35 );\n imagedestroy( $resource );\n}\n</code></pre>\n\n<p>in a standalone PHP script, to make sure it's not a PHP or GD related issue.</p>\n\n<p>PS: <a href=\"https://wordpress.stackexchange.com/questions/163844/create-image-formats-with-different-qualities-when-uploading/165241#165241\">Here's a different approach</a> where we try to modify the image quality <strong>before</strong> the image size is generated.</p>\n\n<p><strong>Testing the plugin</strong></p>\n\n<p>Let's check the plugin from the main question.</p>\n\n<p>Test install</p>\n\n<ul>\n<li>WordPress version 4.9-alpha-40917</li>\n<li>PHP 7.0.19</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/T7rb5.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/T7rb5.jpg\" alt=\"gd\"></a>\n<a href=\"https://i.stack.imgur.com/mzBEk.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mzBEk.jpg\" alt=\"imagick\"></a></p>\n\n<p>Here's the generated <code>hello-image</code> (670x300) size, of the SMALL (670 × 377) image, from the question, where we set the quality to 40:</p>\n\n<pre><code>imagejpeg( $resource, $image, 40 );\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/NLSvs.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NLSvs.jpg\" alt=\"q=40\"></a></p>\n\n<p>Here's the same but with the quality set to 0:</p>\n\n<pre><code>imagejpeg( $resource, $image, 0 );\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/cCVOu.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cCVOu.jpg\" alt=\"q=0\"></a></p>\n\n<p>So it looks like we <strong>don't</strong> get the same behavior as described in the question, that when the quality is set to 40, it becomes 0, for the <code>hello-image</code> size of the 670x377 original image.</p>\n"
}
]
| 2017/06/24 | [
"https://wordpress.stackexchange.com/questions/271195",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24875/"
]
| I have a [custom image size](https://developer.wordpress.org/reference/functions/add_image_size/) `hello-image`:
```
add_image_size( 'hello-image', 700, 300, true );
```
Whenever an image is uploaded, I compress the cropped `hello-image` sized image to `40%` JPEG compression. It works great in all cases except...
The problem
-----------
If the **width** of the original image is *greater* than `700px` it works just fine. But if the width of it is *less* than `700px`, the compression goes to around `0%`.
How to test it
--------------
Download the following two images:
[BIG: 784px × 441px](https://i.imgur.com/4QJjEMW.jpg)
[SMALL: 670px × 377px](https://i.imgur.com/J9SOdQe.jpg)
Then I have created a plugin which has all the relevant code:
```
<?php
/*
Plugin Name: WPSE: custom image size and JPEG compression
Description: custom image size and JPEG compression
Author: WPSE
Version: 1.0
*/
// Set JPEG compression quality
add_filter('jpeg_quality', create_function('$quality', 'return 100;'));
add_action('added_post_meta', 'ad_update_jpeg_quality', 10, 4);
function ad_update_jpeg_quality($meta_id, $attach_id, $meta_key, $attach_meta) {
if ($meta_key == '_wp_attachment_metadata') {
$post = get_post($attach_id);
if ($post->post_mime_type == 'image/jpeg' && is_array($attach_meta['sizes'])) {
$pathinfo = pathinfo($attach_meta['file']);
$uploads = wp_upload_dir();
$dir = $uploads['basedir'] . '/' . $pathinfo['dirname'];
foreach ($attach_meta['sizes'] as $size => $value) {
$image = $dir . '/' . $value['file'];
$resource = imagecreatefromjpeg($image);
if ($size == 'large') {
// set the jpeg quality for 'large' size
imagejpeg($resource, $image, 35);
} elseif ($size == 'medium') {
// set the jpeg quality for the 'medium' size
imagejpeg($resource, $image, 35);
} elseif ($size == 'hello-image') {
// set the jpeg quality for the 'hello-image' size
imagejpeg($resource, $image, 40);
} else {
// set the jpeg quality for the rest of sizes
imagejpeg($resource, $image, 35); // 38
}
imagedestroy($resource);
}
}
}
}
// add custom image sizes to media uploader
function my_insert_custom_image_sizes( $sizes ) {
// get the custom image sizes
global $_wp_additional_image_sizes;
// if there are none, just return the built-in sizes
if ( empty( $_wp_additional_image_sizes ) )
return $sizes;
// add all the custom sizes to the built-in sizes
foreach ( $_wp_additional_image_sizes as $id => $data ) {
// take the size ID (e.g., 'my-name'), replace hyphens with spaces,
// and capitalise the first letter of each word
if ( !isset($sizes[$id]) )
$sizes[$id] = ucfirst( str_replace( '-', ' ', $id ) );
}
return $sizes;
}
// Which custom image size selected by default
function my_set_default_image_size () {
return 'hello-image';
}
function custom_image_setup () {
// custom image sizes
add_image_size( 'medium', 300, 9999 ); // medium
add_image_size( 'hello-image', 700, 300, true ); // custom
add_image_size( 'large', 700, 3000 ); // large
add_filter( 'image_size_names_choose', 'my_insert_custom_image_sizes' );
add_filter( 'pre_option_image_default_size', 'my_set_default_image_size' );
}
add_action( 'after_setup_theme', 'custom_image_setup' );
```
Now, upload the *big* image and see how the `hello-image` image is compressed fine. Then upload the *small* image and see how the same image size is compressed terribly. So to clarify, this is the results:
```
700x300 = 40% compression
670x300 = 0% compression
```
Both of which are generated via the exact same custom image size. What is the cause of this and how can it be fixed?
I should highlight that my colleague posted a [question here](https://wordpress.stackexchange.com/questions/271192/add-image-size-cropped-only-if-width-of-the-image-matches-or-is-higher) asking how to avoid creating this image size if the width is lower than `700px`... but I'm a WordPress geek who would rather resolve the cause of the problem than add a hacky fix to it.
Finally, I started seeing this problem in a recent WordPress update, so it may be a bug in core, as opposed to an issue in my code.
**Edit**: Read the [update](https://wordpress.stackexchange.com/questions/271195/setting-jpeg-compression-for-custom-image-sizes-doesnt-work-in-specific-cases#comment402886_271261). | *Some suggestions:*
If you want to try out the *Image Editor API* you can try to replace
```
imagejpeg( $resource, $image, 35 );
```
with:
```
$editor = wp_get_image_editor( $image );
if ( ! is_wp_error( $editor ) )
{
$editor->set_quality( 35 );
$editor->save( $image );
}
unset( $editor );
```
Also try to test e.g. these parts:
```
$resource = imagecreatefromjpeg( $image );
if( false !== $resource )
{
imagejpeg( $resource, $image, 35 );
imagedestroy( $resource );
}
```
in a standalone PHP script, to make sure it's not a PHP or GD related issue.
PS: [Here's a different approach](https://wordpress.stackexchange.com/questions/163844/create-image-formats-with-different-qualities-when-uploading/165241#165241) where we try to modify the image quality **before** the image size is generated.
**Testing the plugin**
Let's check the plugin from the main question.
Test install
* WordPress version 4.9-alpha-40917
* PHP 7.0.19
[](https://i.stack.imgur.com/T7rb5.jpg)
[](https://i.stack.imgur.com/mzBEk.jpg)
Here's the generated `hello-image` (670x300) size, of the SMALL (670 × 377) image, from the question, where we set the quality to 40:
```
imagejpeg( $resource, $image, 40 );
```
[](https://i.stack.imgur.com/NLSvs.jpg)
Here's the same but with the quality set to 0:
```
imagejpeg( $resource, $image, 0 );
```
[](https://i.stack.imgur.com/cCVOu.jpg)
So it looks like we **don't** get the same behavior as described in the question, that when the quality is set to 40, it becomes 0, for the `hello-image` size of the 670x377 original image. |
271,226 | <p>I am currently trying my hand at creating a WP theme using angular JS.
I am trying to work through this tutorial: <a href="https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/" rel="nofollow noreferrer">https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/</a></p>
<p>However, I am near the end of this, and my ng-repeat is not returning a list of my posts.</p>
<p>This is my scripts.js: </p>
<pre><code>angular.module('app', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: myLocalized.partials + 'main.html',
controller: 'Main'
})
.when('/:ID', {
templateUrl: myLocalized.partials + 'content.html',
controller: 'Content'
});
})
.controller('Main', function($scope, $http, $routeParams) {
$http.get('wp-json/wp/v2/posts/').then(function(res){
$scope.posts = res;
});
})
.controller('Content', function($scope, $http, $routeParams) {
$http.get('wp-json/wp/v2/posts' + $routeParams.id).then(function(res){
$scope.post = res;
});
});
</code></pre>
<p>And this is the code from my main.html:</p>
<pre><code><div ng-controller="Main">
<strong>This is the main page</strong>
<ul>
<li ng-repeat="post in posts">
<a href="{{ post.id }}">{{ post.title }}</a>
</li>
</ul>
</div>
</code></pre>
<p>However, when I navigate to my page I only see:</p>
<p><a href="https://i.stack.imgur.com/smkkk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/smkkk.png" alt="enter image description here"></a></p>
<p>All the scripts seem to be enqueued correctly, and index.php is pulling main.html through, it just doesn't work.</p>
<p>I know it'll be something obvious, but my google foo has let me down </p>
| [
{
"answer_id": 271227,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 1,
"selected": false,
"text": "<p>Looking at the post format generated by the REST API I think you should access the title like:</p>\n\n<pre><code> <li ng-repeat=\"post in posts\">\n <a href=\"{{ post.id }}\">{{ post.title.rendered }}</a>\n </li>\n</code></pre>\n"
},
{
"answer_id": 271298,
"author": "hmakein",
"author_id": 49874,
"author_profile": "https://wordpress.stackexchange.com/users/49874",
"pm_score": 1,
"selected": true,
"text": "<p>It looks like the tutorial you linked is using <code>success</code>, and you've changed it to <code>then</code>. </p>\n\n<p>The <code>success</code> method has been <a href=\"https://code.angularjs.org/1.5.10/docs/api/ng/service/$http#deprecation-notice\" rel=\"nofollow noreferrer\">deprecated</a>, so you were correct to do that. However, because <code>then</code> returns data a little differently from <code>success</code>, you'll need to update your <code>$scope.post</code> variable accordingly:</p>\n\n<p><code>$scope.post = res.data;</code></p>\n\n<p>You can find a great explanation for the change in <a href=\"https://stackoverflow.com/a/35331339/3194942\">this answer</a>.</p>\n"
}
]
| 2017/06/24 | [
"https://wordpress.stackexchange.com/questions/271226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122535/"
]
| I am currently trying my hand at creating a WP theme using angular JS.
I am trying to work through this tutorial: <https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/>
However, I am near the end of this, and my ng-repeat is not returning a list of my posts.
This is my scripts.js:
```
angular.module('app', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: myLocalized.partials + 'main.html',
controller: 'Main'
})
.when('/:ID', {
templateUrl: myLocalized.partials + 'content.html',
controller: 'Content'
});
})
.controller('Main', function($scope, $http, $routeParams) {
$http.get('wp-json/wp/v2/posts/').then(function(res){
$scope.posts = res;
});
})
.controller('Content', function($scope, $http, $routeParams) {
$http.get('wp-json/wp/v2/posts' + $routeParams.id).then(function(res){
$scope.post = res;
});
});
```
And this is the code from my main.html:
```
<div ng-controller="Main">
<strong>This is the main page</strong>
<ul>
<li ng-repeat="post in posts">
<a href="{{ post.id }}">{{ post.title }}</a>
</li>
</ul>
</div>
```
However, when I navigate to my page I only see:
[](https://i.stack.imgur.com/smkkk.png)
All the scripts seem to be enqueued correctly, and index.php is pulling main.html through, it just doesn't work.
I know it'll be something obvious, but my google foo has let me down | It looks like the tutorial you linked is using `success`, and you've changed it to `then`.
The `success` method has been [deprecated](https://code.angularjs.org/1.5.10/docs/api/ng/service/$http#deprecation-notice), so you were correct to do that. However, because `then` returns data a little differently from `success`, you'll need to update your `$scope.post` variable accordingly:
`$scope.post = res.data;`
You can find a great explanation for the change in [this answer](https://stackoverflow.com/a/35331339/3194942). |
271,244 | <p>My wp-config.php already has </p>
<pre><code>define('ALLOW_UNFILTERED_UPLOADS', true);
</code></pre>
<p>But when I upload a .nb file, it shows "This file type is not allowed. Please try another"</p>
<p>How do I allow to upload any type of files? My WP version is 4.7.3.</p>
| [
{
"answer_id": 271246,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<h3>Original Answer</h3>\n\n<p>Add the code below to your current theme's <code>functions.php</code>:</p>\n\n<pre><code>function wpse_add_nb_mime_type( $allowed_mimes ) {\n $allowed_mimes['nb'] = 'application/mathematica';\n return $allowed_mimes;\n}\nadd_filter( 'mime_types', 'wpse_add_nb_mime_type', 10, 1 );\n</code></pre>\n\n<p>Remove <code>define</code>, mentioned in your question, from <code>wp-config.php</code>. Now you should be able to upload <code>.nb</code> files.</p>\n\n<p><strong>Plugin alternative</strong>: to make the code above, immune to theme changes, it's better to put it into a plugin. Create new file <code>wpse-addnbmimetype.php</code>, with this content:</p>\n\n<pre><code><?php\n/*\nPlugin Name: WPSE Add NB Mime Type\nDescription: Adds 'nb' => 'application/mathematica' to allowable mime types\n*/\nfunction wpse_add_nb_mime_type( $allowed_mimes ) {\n $allowed_mimes['nb'] = 'application/mathematica';\n return $allowed_mimes;\n}\n\nfunction wpse_prepare_add_nb_mime_type() {\n // this filter can be added as early as in init action\n add_filter( 'mime_types', 'wpse_add_nb_mime_type', 10, 1 );\n}\nadd_action( 'init', 'wpse_prepare_add_nb_mime_type' );\n</code></pre>\n\n<p>Put this file into '/wp-content/mu-plugins/' folder. Now you can switch themes, without losing ability to upload .nb files.</p>\n\n<h3>Analysis</h3>\n\n<p>Read comments to @majick's answer, first. After all corrections, his filter will look like this:</p>\n\n<pre><code>add_filter('upload_mimes', 'modify_upload_mimes', 10, 2);\nfunction modify_upload_mimes($t, $user) {\n if ($user == null) {$user = wp_get_current_user();}\n if (in_array('administrator', $user->roles)) {\n $t['nb'] = 'application/mathematica';\n }\n return $t;\n}\n</code></pre>\n\n<p>Does it work? Yes, but it does restrict uploads of files with .nb extensions to 'administrator' role only. Authors and editors will not be able to upload such files. Let's change it, by replacing line:</p>\n\n<pre><code>if (in_array('administrator', $user->roles)) {\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if ( $user->has_cap( 'upload_files' ) ) {\n</code></pre>\n\n<p>Now, authors, editors, and administrators can upload .nb files. </p>\n\n<p>Checks against user's role should be discouraged, and should be made against user's capabilities, instead. If one day, we decide to add 'upload_files' capability to contributor's role ( all contributors ), or to the individual user, our filter will work, without changes.</p>\n\n<p>Why do we have two hooks, 'mime_types' and 'upload_mimes', to choose from? It is recommended, to use 'mime_types' for adding mime types, and 'upload_mimes' for removing ( to unset ) them.</p>\n\n<p>There are two functions in '/wp-includes/functions.php': first -\n <code>get_allowed_mime_types( $user = null )</code>, introducing 'upload_mimes' filter hook, which was intended for arbitrary removal of 'swf', 'exe', and conditional removal of 'htm|html', mime types, and second - <code>wp_get_mime_types()</code>, introducing 'mime_types' filter hook, intended for adding mime types.</p>\n\n<h3>Conclusion</h3>\n\n<p>Technically, we could use either hook for our solution, but according to recommendations, 'mime_types' should be used. No checks for user's capabilities are necessary, as both hooks will be triggered for users with 'upload_files' capability, only.</p>\n"
},
{
"answer_id": 271248,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to debug this by doing the following:</p>\n\n<pre><code>apply_filters('user_has_cap', 'check_user_caps', 10, 4);\nfunction check_user_caps($allcaps, $caps, $args, $user) {\n if (in_array('administrator', $user->roles)) {\n echo \"<!-- Admin Caps: \"; print_r($allcaps); echo \" -->\";\n }\n return $allcaps;\n}\n</code></pre>\n\n<p>Then check your page source and look for 'unfiltered_upload' capability. It should be there, if not something is going wrong...</p>\n\n<p>The other way to do this is using the <code>upload_mimes</code> filter. This is probably a better way to go since you can add <em>just</em> the extension(s) you need and so is a much more secure way of going. eg:</p>\n\n<pre><code>add_filter('upload_mimes', 'modify_upload_mimes', 10, 2);\nfunction modify_upload_mimes($t, $user) {\n if ($user == null) {$user = wp_get_current_user();}\n if (in_array('administrator', $user->roles)) {\n $t['nb'] = 'application/mathematica';\n }\n return $t;\n}\n</code></pre>\n\n<p>see function <code>get_allowed_mime_types</code> in <code>wp-includes/functions.php</code></p>\n"
}
]
| 2017/06/24 | [
"https://wordpress.stackexchange.com/questions/271244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58945/"
]
| My wp-config.php already has
```
define('ALLOW_UNFILTERED_UPLOADS', true);
```
But when I upload a .nb file, it shows "This file type is not allowed. Please try another"
How do I allow to upload any type of files? My WP version is 4.7.3. | ### Original Answer
Add the code below to your current theme's `functions.php`:
```
function wpse_add_nb_mime_type( $allowed_mimes ) {
$allowed_mimes['nb'] = 'application/mathematica';
return $allowed_mimes;
}
add_filter( 'mime_types', 'wpse_add_nb_mime_type', 10, 1 );
```
Remove `define`, mentioned in your question, from `wp-config.php`. Now you should be able to upload `.nb` files.
**Plugin alternative**: to make the code above, immune to theme changes, it's better to put it into a plugin. Create new file `wpse-addnbmimetype.php`, with this content:
```
<?php
/*
Plugin Name: WPSE Add NB Mime Type
Description: Adds 'nb' => 'application/mathematica' to allowable mime types
*/
function wpse_add_nb_mime_type( $allowed_mimes ) {
$allowed_mimes['nb'] = 'application/mathematica';
return $allowed_mimes;
}
function wpse_prepare_add_nb_mime_type() {
// this filter can be added as early as in init action
add_filter( 'mime_types', 'wpse_add_nb_mime_type', 10, 1 );
}
add_action( 'init', 'wpse_prepare_add_nb_mime_type' );
```
Put this file into '/wp-content/mu-plugins/' folder. Now you can switch themes, without losing ability to upload .nb files.
### Analysis
Read comments to @majick's answer, first. After all corrections, his filter will look like this:
```
add_filter('upload_mimes', 'modify_upload_mimes', 10, 2);
function modify_upload_mimes($t, $user) {
if ($user == null) {$user = wp_get_current_user();}
if (in_array('administrator', $user->roles)) {
$t['nb'] = 'application/mathematica';
}
return $t;
}
```
Does it work? Yes, but it does restrict uploads of files with .nb extensions to 'administrator' role only. Authors and editors will not be able to upload such files. Let's change it, by replacing line:
```
if (in_array('administrator', $user->roles)) {
```
with:
```
if ( $user->has_cap( 'upload_files' ) ) {
```
Now, authors, editors, and administrators can upload .nb files.
Checks against user's role should be discouraged, and should be made against user's capabilities, instead. If one day, we decide to add 'upload\_files' capability to contributor's role ( all contributors ), or to the individual user, our filter will work, without changes.
Why do we have two hooks, 'mime\_types' and 'upload\_mimes', to choose from? It is recommended, to use 'mime\_types' for adding mime types, and 'upload\_mimes' for removing ( to unset ) them.
There are two functions in '/wp-includes/functions.php': first -
`get_allowed_mime_types( $user = null )`, introducing 'upload\_mimes' filter hook, which was intended for arbitrary removal of 'swf', 'exe', and conditional removal of 'htm|html', mime types, and second - `wp_get_mime_types()`, introducing 'mime\_types' filter hook, intended for adding mime types.
### Conclusion
Technically, we could use either hook for our solution, but according to recommendations, 'mime\_types' should be used. No checks for user's capabilities are necessary, as both hooks will be triggered for users with 'upload\_files' capability, only. |
271,258 | <p>What i want to get and have no clue how start is:</p>
<p>Query posts (for example from specific category, ordered by date) but to have the posts from same author numbered by there count in that posts list.</p>
<blockquote>
<p><strong>For example:</strong></p>
<p><strong>Date:</strong> 1/8/2017 <strong>Title:</strong> Great post <strong>Author:</strong> John <strong>Number:</strong> 1</p>
<p><strong>Date:</strong> 1/7/2017 <strong>Title:</strong> Thrilling post <strong>Author:</strong> Mike <strong>Number:</strong> 1</p>
<p><strong>Date:</strong> 1/6/2017 <strong>Title:</strong> New post <strong>Author:</strong> John <strong>Number:</strong> 2</p>
<p><strong>Date:</strong> 1/5/2017 <strong>Title:</strong> Exiting post <strong>Author:</strong> Nathan <strong>Number:</strong> 1</p>
<p><strong>Date:</strong> 1/4/2017 <strong>Title:</strong> Best post <strong>Author:</strong> Gandi <strong>Number:</strong> 1</p>
<p><strong>Date:</strong> 1/3/2017 <strong>Title:</strong> Boring post <strong>Author:</strong> John <strong>Number:</strong> 3</p>
<p><strong>Date:</strong> 1/2/2017 <strong>Title:</strong> Amazing post <strong>Author:</strong> Gandi <strong>Number:</strong> 2</p>
<p><strong>Date:</strong> 1/1/2017 <strong>Title:</strong> Another post <strong>Author:</strong> Michael <strong>Number:</strong> 1</p>
</blockquote>
<p>Of course i'm looking for an elegant, shortest code possible, simple way.</p>
<p><strong>Edit:</strong> I thought of an idea:
Maybe i can somehow use the author id as a new variable name, adding to this variable each post loop (while) and echoing it.</p>
<p>So i tried:</p>
<pre><code>++${the_author_meta( ID )}; echo ${the_author_meta( ID )};
</code></pre>
<p>which i thought would create a variable named by the author id (for example: <code>$465</code>) and would add to it 1 (so <code>$465 = 1</code>) and echo '1'. but it doesn't :) actually <code>++${the_author_meta( ID )};</code> it self echoes the author id twice...</p>
| [
{
"answer_id": 271260,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": 0,
"selected": false,
"text": "<p>If you have deleted the posts, you can't no longer access it. If you would like to verify your deleted post are available or not, you could check in your wordpress database table named -> <strong>prefix_posts</strong> (table) and check <strong>post_status</strong> column. If you found your post is still in trash in that column. Make that <strong>trash</strong> to <strong>publish</strong>.</p>\n"
},
{
"answer_id": 271267,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 1,
"selected": false,
"text": "<p>If your post isn't in Trash, then it was completely deleted. The only way to restore it is recovering your database from an earlier backup. If you don't have backups and your post was deleted from the database - there is no way to restore it.</p>\n"
},
{
"answer_id": 326150,
"author": "Inarvo Solutions",
"author_id": 159428,
"author_profile": "https://wordpress.stackexchange.com/users/159428",
"pm_score": 0,
"selected": false,
"text": "<p>Your hosting account may have a daily backup of database. So please </p>\n\n<ol>\n<li>Login to your account </li>\n<li>Select Backup Restore</li>\n<li>Select the date to recover from (in your case previous day) </li>\n<li>Restore database.\nand you would see your deleted page back in your dashboard. </li>\n</ol>\n\n<p>P.S : Responding to this post though old one, so that it helps someone looking for it. </p>\n"
},
{
"answer_id": 326156,
"author": "Abhijeet Kumar",
"author_id": 149045,
"author_profile": "https://wordpress.stackexchange.com/users/149045",
"pm_score": 0,
"selected": false,
"text": "<p>If your post isn't in the thrash section then it would have been deleted permanently. The only way to restore it is by rolling out to the previous back up . Else I am afraid you have to redo the task again.</p>\n"
}
]
| 2017/06/25 | [
"https://wordpress.stackexchange.com/questions/271258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122089/"
]
| What i want to get and have no clue how start is:
Query posts (for example from specific category, ordered by date) but to have the posts from same author numbered by there count in that posts list.
>
> **For example:**
>
>
> **Date:** 1/8/2017 **Title:** Great post **Author:** John **Number:** 1
>
>
> **Date:** 1/7/2017 **Title:** Thrilling post **Author:** Mike **Number:** 1
>
>
> **Date:** 1/6/2017 **Title:** New post **Author:** John **Number:** 2
>
>
> **Date:** 1/5/2017 **Title:** Exiting post **Author:** Nathan **Number:** 1
>
>
> **Date:** 1/4/2017 **Title:** Best post **Author:** Gandi **Number:** 1
>
>
> **Date:** 1/3/2017 **Title:** Boring post **Author:** John **Number:** 3
>
>
> **Date:** 1/2/2017 **Title:** Amazing post **Author:** Gandi **Number:** 2
>
>
> **Date:** 1/1/2017 **Title:** Another post **Author:** Michael **Number:** 1
>
>
>
Of course i'm looking for an elegant, shortest code possible, simple way.
**Edit:** I thought of an idea:
Maybe i can somehow use the author id as a new variable name, adding to this variable each post loop (while) and echoing it.
So i tried:
```
++${the_author_meta( ID )}; echo ${the_author_meta( ID )};
```
which i thought would create a variable named by the author id (for example: `$465`) and would add to it 1 (so `$465 = 1`) and echo '1'. but it doesn't :) actually `++${the_author_meta( ID )};` it self echoes the author id twice... | If your post isn't in Trash, then it was completely deleted. The only way to restore it is recovering your database from an earlier backup. If you don't have backups and your post was deleted from the database - there is no way to restore it. |
271,289 | <p>In a clean WordPress installation, how do you add meta keywords and meta description in head tag of my WordPress pages? There aren't any fields for these.</p>
<p>I don't want to touch my code since I'm new to WordPress. I want to do this only by WordPress itself.</p>
| [
{
"answer_id": 271301,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 0,
"selected": false,
"text": "<p>If you meaning how you could add the html tags to header:</p>\n\n<ol>\n<li>You could or copy the file header.php into a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a></li>\n<li>Or use <a href=\"https://developer.wordpress.org/reference/functions/add_action/\" rel=\"nofollow noreferrer\">add_action</a> into <a href=\"https://codex.wordpress.org/Function_Reference/wp_head\" rel=\"nofollow noreferrer\">wp_head</a></li>\n</ol>\n"
},
{
"answer_id": 271307,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>I assume you are trying to add metadata to the header, such as Open Graph. To do so, you can hook into <code>wp_head</code> and output your content there directly. Add this piece of code to your theme's (or your child theme's) <code>functions.php</code> file:</p>\n\n<pre><code>//Hook to wp_head\nadd_action('wp_head','add_my_metadata');\nfunction add_my_metadata(){\n // Echo any content your wish here. Replace this with what you want.\n echo '<meta name=\"keywords\" content=\"Keyword1, Keyword2\"/>';\n}\n</code></pre>\n\n<p>Notice, that your theme must have <code><?php wp_head(); ?></code> in its <code>header.php</code> file in order for you to be able to output any content there.</p>\n\n<h2>UPDATE</h2>\n\n<p>If you are new to WordPress, you can install a plugin. There are plenty of known plugins that can do this for you, the most distinguished one is <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">Yoast SEO</a> which automatically does this for you.</p>\n"
}
]
| 2017/06/25 | [
"https://wordpress.stackexchange.com/questions/271289",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22989/"
]
| In a clean WordPress installation, how do you add meta keywords and meta description in head tag of my WordPress pages? There aren't any fields for these.
I don't want to touch my code since I'm new to WordPress. I want to do this only by WordPress itself. | I assume you are trying to add metadata to the header, such as Open Graph. To do so, you can hook into `wp_head` and output your content there directly. Add this piece of code to your theme's (or your child theme's) `functions.php` file:
```
//Hook to wp_head
add_action('wp_head','add_my_metadata');
function add_my_metadata(){
// Echo any content your wish here. Replace this with what you want.
echo '<meta name="keywords" content="Keyword1, Keyword2"/>';
}
```
Notice, that your theme must have `<?php wp_head(); ?>` in its `header.php` file in order for you to be able to output any content there.
UPDATE
------
If you are new to WordPress, you can install a plugin. There are plenty of known plugins that can do this for you, the most distinguished one is [Yoast SEO](https://wordpress.org/plugins/wordpress-seo/) which automatically does this for you. |
271,293 | <p>The theme I'm using makes extensive use of internal stylesheets to style various types of pages and their elements. For example, through their plugin UI, I can configure a specific page's hero layout and content... including font, size and color for various text elements. After configuring the hero and publishing the page, an internal stylesheet is added to the page's <code><head></code> tag:</p>
<pre><code><style id="ut-hero-custom-css" type="text/css">
#ut-hero .hero-inner {
text-align: right
}
.hero-description {
color: #000000;
}
.hero-description {
background: #FCB54B;
padding-bottom: 0;
margin-bottom: 5px;
}
#ut-hero .hero-title {
color: #1777FF;
}
</style>
</code></pre>
<p>Unfortunately, the plugin is limited in what it allows me to customize so I need to add some of my own CSS to fine tune things. Let's say I want to display a border around the block of text with <code>class="hero-description"</code>. I'd need to add </p>
<pre><code>.hero-description {
border: 1px solid #c00;
}
</code></pre>
<p>and have it be applied to the page AFTER the initial declaration above. Adding it my child-theme's style.css file or any other CSS file I register and enqueue adds it BEFORE. I was hoping that I could specify the inline stylesheet embedded by the plugin as a dependency for my new CSS file when enqueueing it, but I don't see any handle or reference to it in $wp_styles so I couldn't do that. Can you even register an internal stylesheet? </p>
<p>Anyway, this can be broken down to a very general problem. I want to have the "last word" on the page's CSS (excluding inline styles and scoped elements). Is there not a direct way to specify that a line of code such as:</p>
<pre><code><link rel="stylesheet" src="mycss.css">
</code></pre>
<p>always be included right before the closing <code></head></code> tag? </p>
| [
{
"answer_id": 271309,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>You would add dependencies to your <code>wp_enqueue_style()</code> function calls.</p>\n\n<pre><code>function my_enqueues() {\n wp_enqueue_style( 'style-one', '{path}' );\n wp_enqueue_style( 'style-two', '{path}', array( 'style-one' ) );\n wp_enqueue_style( 'style-three', '{path}', array( 'style-two' ) );\n wp_enqueue_style( 'style-final', '{path}', array( 'style-three' ) );\n}\nadd_action( 'wp_enqueue_scripts', 'my_enqueues' );\n</code></pre>\n\n<p>What this code does is make each style sheet dependent on the previous one. So they will load in the order <code>style-one</code>, <code>style-two</code>, etc.</p>\n\n<p>Of course one of the <code>{path}</code> placeholders should be your <code>style.css</code> file called with <code>get_stylesheet_uri();</code>.</p>\n\n<p>If you want to load one after a plugin has loaded one that overrides, then try using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded\" rel=\"nofollow noreferrer\"><code>plugins_loaded</code></a> hook:</p>\n\n<pre><code>function my_plugin_overrides() {\n wp_deregister_style( 'plugin-styles' ); // OPTIONAL\n wp_enqueue_style( 'plugin-css-overrides', '{path}', array( 'deps' ) );\n}\nadd_action( 'plugins_loaded', 'my_plugin_overrides' );\n</code></pre>\n"
},
{
"answer_id": 271524,
"author": "Daveh0",
"author_id": 118789,
"author_profile": "https://wordpress.stackexchange.com/users/118789",
"pm_score": 0,
"selected": false,
"text": "<p>I am completely blocked here. SO, for the time being I will be using the following \"workaround\" so that I can at least continue development:</p>\n\n<pre><code>$(function() {\n $('head').append('\n <link rel=\"stylesheet\" type=\"text/css\" src=\"mycss.css\">\n ');\n});\n</code></pre>\n\n<p>Definitely not the \"right\" way, but I should be able to easily port my new, overriding styles (as referenced in mycss.css above) to wherever they belong when done the \"right\" way when I get it figured out.</p>\n"
},
{
"answer_id": 289027,
"author": "Kalamun",
"author_id": 131986,
"author_profile": "https://wordpress.stackexchange.com/users/131986",
"pm_score": 1,
"selected": false,
"text": "<p>It's not elegant but it works.</p>\n\n<p>Add these lines to functions.php:</p>\n\n<pre><code>ob_start();\n\nadd_action('shutdown', function() {\n $final = '';\n $levels = ob_get_level();\n for ($i = 0; $i < $levels; $i++) {\n $final .= ob_get_clean();\n }\n\n // append styles just before </head>\n $final = str_replace( \"</head>\", '<link rel=\"stylesheet\" src=\"mycss.css\"></head>', $final );\n\n echo $final;\n}, 0);\n</code></pre>\n\n<p>Alternatively you can move all the inline styles at the beginning of the head, better if just after the title tag:</p>\n\n<pre><code>ob_start();\n\nadd_action('shutdown', function() {\n $final = '';\n $levels = ob_get_level();\n for ($i = 0; $i < $levels; $i++) {\n $final .= ob_get_clean();\n }\n\n /* Adjust the final output */\n\n // load HTML DOM\n $dom= new DOMDocument(); \n $dom->preserveWhiteSpace = false;\n $dom->formatOutput = true;\n $dom->loadHTML( '<?xml encoding=\"utf-8\" ?>' . $final );\n\n // collect styles and remove them from DOM\n $inline_styles = \"\";\n $styles = $dom->getElementsByTagName(\"style\");\n foreach( $styles as $style )\n {\n $inline_styles .= $dom->saveHTML( $style );\n $style->parentNode->removeChild( $style );\n }\n\n $final = $dom->saveHTML();\n\n // strip utf-8 workaround\n $final = str_replace( '<?xml encoding=\"utf-8\" ?>', \"\", $final );\n\n // append styles after <title>\n $final = str_replace( \"</title>\", \"</title>\\n\" . $inline_styles, $final );\n\n echo $final;\n}, 0);\n</code></pre>\n"
},
{
"answer_id": 289100,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 0,
"selected": false,
"text": "<p>Since WP 4.7 the WP dashboard includes a CSS customizer (Appearence->Cusomize->Additional CSS). This <em>might</em> be a solution for your theme specific CSS as WP adds the style block to <head> after enqueued CSS and possibly other additions by theme.</p>\n\n<p>Normal practice as per Cedons enqueing answer or jimihenrik's comment should work.</p>\n\n<p>However; it appears this theme needs a \"non-standard\" solution (I like your JS solution) - alternatives include an edited copy of header.php in child theme.</p>\n\n<blockquote>\n <p>\"an internal stylesheet is added to the page's <head>\"</p>\n</blockquote>\n\n<p>The theme could be adding in a variety of ways in header.php e.g. hard coding; via a theme \"action hook\"; via wp-head</p>\n\n<p>The last part of header.php typically contains:</p>\n\n<pre><code><?php possibly_themes_own_action_hook(); ?>\n<?php wp_head(); ?>\n</head>\n<body <?php body_class(); ?>>\n Some HTML for header and navigation & other stuff prior to Loop adding say H1 title\n</code></pre>\n\n<p>If theme does not have header.php or it is missing <code></head></code> then relevant code is probably in templates.</p>\n\n<p>In your child header.php <strong>just above <code></head></code></strong> (if not present see below) you could either:</p>\n\n<ul>\n<li>hard code your CSS or stylesheet link above <code></head></code> </li>\n<li><p><strong>or</strong> <code><php include('path/to/mycss.css');?></code></p></li>\n<li><p><strong>or</strong> add your own action:</p>\n\n<pre><code> my_add_to_head(); \n</code></pre>\n\n<p>and in your functions.php</p>\n\n<pre><code> function my_head_function() {\n ?>\n <style>.hero-description {border:1px solid #c00;}</style> \n <?php\n // or stylesheet link or file_get_contents to get css file and echo\n // + any other stuff you want to add to head\n }\n add_action('my_add_to_head', 'my_head_function');\n</code></pre></li>\n</ul>\n\n<p>Solutions are <strong>bad practice</strong> especially if someone else ends up having to maintain but may be the best option with your theme.</p>\n\n<blockquote>\n <p>\"when i used wp_head, it ended up in the tag with all the\n JavaScript files.\"</p>\n</blockquote>\n\n<p>If you mean within the body tag then there is a coding error in the theme. Otherwise it is \"non-standard\" design and could cause many plugins to \"fail\". Either <code>wp_head();</code> is after the body tag or \"wp_head\" is used to insert <code><body></code> and maybe <code></head></code>. </p>\n\n<p>If <code></head></code> is not in header.php or templates then adding the above \"solutions\" just above <code>wp_head();</code> <em>might</em> still work but plugin issues will remain.</p>\n"
}
]
| 2017/06/25 | [
"https://wordpress.stackexchange.com/questions/271293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118789/"
]
| The theme I'm using makes extensive use of internal stylesheets to style various types of pages and their elements. For example, through their plugin UI, I can configure a specific page's hero layout and content... including font, size and color for various text elements. After configuring the hero and publishing the page, an internal stylesheet is added to the page's `<head>` tag:
```
<style id="ut-hero-custom-css" type="text/css">
#ut-hero .hero-inner {
text-align: right
}
.hero-description {
color: #000000;
}
.hero-description {
background: #FCB54B;
padding-bottom: 0;
margin-bottom: 5px;
}
#ut-hero .hero-title {
color: #1777FF;
}
</style>
```
Unfortunately, the plugin is limited in what it allows me to customize so I need to add some of my own CSS to fine tune things. Let's say I want to display a border around the block of text with `class="hero-description"`. I'd need to add
```
.hero-description {
border: 1px solid #c00;
}
```
and have it be applied to the page AFTER the initial declaration above. Adding it my child-theme's style.css file or any other CSS file I register and enqueue adds it BEFORE. I was hoping that I could specify the inline stylesheet embedded by the plugin as a dependency for my new CSS file when enqueueing it, but I don't see any handle or reference to it in $wp\_styles so I couldn't do that. Can you even register an internal stylesheet?
Anyway, this can be broken down to a very general problem. I want to have the "last word" on the page's CSS (excluding inline styles and scoped elements). Is there not a direct way to specify that a line of code such as:
```
<link rel="stylesheet" src="mycss.css">
```
always be included right before the closing `</head>` tag? | It's not elegant but it works.
Add these lines to functions.php:
```
ob_start();
add_action('shutdown', function() {
$final = '';
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
// append styles just before </head>
$final = str_replace( "</head>", '<link rel="stylesheet" src="mycss.css"></head>', $final );
echo $final;
}, 0);
```
Alternatively you can move all the inline styles at the beginning of the head, better if just after the title tag:
```
ob_start();
add_action('shutdown', function() {
$final = '';
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
/* Adjust the final output */
// load HTML DOM
$dom= new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $final );
// collect styles and remove them from DOM
$inline_styles = "";
$styles = $dom->getElementsByTagName("style");
foreach( $styles as $style )
{
$inline_styles .= $dom->saveHTML( $style );
$style->parentNode->removeChild( $style );
}
$final = $dom->saveHTML();
// strip utf-8 workaround
$final = str_replace( '<?xml encoding="utf-8" ?>', "", $final );
// append styles after <title>
$final = str_replace( "</title>", "</title>\n" . $inline_styles, $final );
echo $final;
}, 0);
``` |
271,295 | <p>Let me start by saying I know there are other posts about this, and a lot of documentation is available for this topic, but none of these resources have helped me to solve my issue.</p>
<p>I'm a beginner at creating plugins for WordPress. This is my first, so I'm sure I'm missing something simple, but everything I have read says this should be working.</p>
<p>The plugin activates no problem, my menu shows up, etc. But the following does not create a new table in the database. I removed everything besides the id just to see if it was the SQL syntax, still no results.</p>
<pre><code>register_activation_hook( __FILE__, 'pf_rb_install' );
function pf_rb_install() {
global $wpdb;
$table_name = $wpdb->prefix . 'pf_parts';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE '$table_name' (
id mediumint(9) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta( $sql );
}
</code></pre>
<p>Thanks in advance for any help.</p>
| [
{
"answer_id": 271309,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>You would add dependencies to your <code>wp_enqueue_style()</code> function calls.</p>\n\n<pre><code>function my_enqueues() {\n wp_enqueue_style( 'style-one', '{path}' );\n wp_enqueue_style( 'style-two', '{path}', array( 'style-one' ) );\n wp_enqueue_style( 'style-three', '{path}', array( 'style-two' ) );\n wp_enqueue_style( 'style-final', '{path}', array( 'style-three' ) );\n}\nadd_action( 'wp_enqueue_scripts', 'my_enqueues' );\n</code></pre>\n\n<p>What this code does is make each style sheet dependent on the previous one. So they will load in the order <code>style-one</code>, <code>style-two</code>, etc.</p>\n\n<p>Of course one of the <code>{path}</code> placeholders should be your <code>style.css</code> file called with <code>get_stylesheet_uri();</code>.</p>\n\n<p>If you want to load one after a plugin has loaded one that overrides, then try using the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded\" rel=\"nofollow noreferrer\"><code>plugins_loaded</code></a> hook:</p>\n\n<pre><code>function my_plugin_overrides() {\n wp_deregister_style( 'plugin-styles' ); // OPTIONAL\n wp_enqueue_style( 'plugin-css-overrides', '{path}', array( 'deps' ) );\n}\nadd_action( 'plugins_loaded', 'my_plugin_overrides' );\n</code></pre>\n"
},
{
"answer_id": 271524,
"author": "Daveh0",
"author_id": 118789,
"author_profile": "https://wordpress.stackexchange.com/users/118789",
"pm_score": 0,
"selected": false,
"text": "<p>I am completely blocked here. SO, for the time being I will be using the following \"workaround\" so that I can at least continue development:</p>\n\n<pre><code>$(function() {\n $('head').append('\n <link rel=\"stylesheet\" type=\"text/css\" src=\"mycss.css\">\n ');\n});\n</code></pre>\n\n<p>Definitely not the \"right\" way, but I should be able to easily port my new, overriding styles (as referenced in mycss.css above) to wherever they belong when done the \"right\" way when I get it figured out.</p>\n"
},
{
"answer_id": 289027,
"author": "Kalamun",
"author_id": 131986,
"author_profile": "https://wordpress.stackexchange.com/users/131986",
"pm_score": 1,
"selected": false,
"text": "<p>It's not elegant but it works.</p>\n\n<p>Add these lines to functions.php:</p>\n\n<pre><code>ob_start();\n\nadd_action('shutdown', function() {\n $final = '';\n $levels = ob_get_level();\n for ($i = 0; $i < $levels; $i++) {\n $final .= ob_get_clean();\n }\n\n // append styles just before </head>\n $final = str_replace( \"</head>\", '<link rel=\"stylesheet\" src=\"mycss.css\"></head>', $final );\n\n echo $final;\n}, 0);\n</code></pre>\n\n<p>Alternatively you can move all the inline styles at the beginning of the head, better if just after the title tag:</p>\n\n<pre><code>ob_start();\n\nadd_action('shutdown', function() {\n $final = '';\n $levels = ob_get_level();\n for ($i = 0; $i < $levels; $i++) {\n $final .= ob_get_clean();\n }\n\n /* Adjust the final output */\n\n // load HTML DOM\n $dom= new DOMDocument(); \n $dom->preserveWhiteSpace = false;\n $dom->formatOutput = true;\n $dom->loadHTML( '<?xml encoding=\"utf-8\" ?>' . $final );\n\n // collect styles and remove them from DOM\n $inline_styles = \"\";\n $styles = $dom->getElementsByTagName(\"style\");\n foreach( $styles as $style )\n {\n $inline_styles .= $dom->saveHTML( $style );\n $style->parentNode->removeChild( $style );\n }\n\n $final = $dom->saveHTML();\n\n // strip utf-8 workaround\n $final = str_replace( '<?xml encoding=\"utf-8\" ?>', \"\", $final );\n\n // append styles after <title>\n $final = str_replace( \"</title>\", \"</title>\\n\" . $inline_styles, $final );\n\n echo $final;\n}, 0);\n</code></pre>\n"
},
{
"answer_id": 289100,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 0,
"selected": false,
"text": "<p>Since WP 4.7 the WP dashboard includes a CSS customizer (Appearence->Cusomize->Additional CSS). This <em>might</em> be a solution for your theme specific CSS as WP adds the style block to <head> after enqueued CSS and possibly other additions by theme.</p>\n\n<p>Normal practice as per Cedons enqueing answer or jimihenrik's comment should work.</p>\n\n<p>However; it appears this theme needs a \"non-standard\" solution (I like your JS solution) - alternatives include an edited copy of header.php in child theme.</p>\n\n<blockquote>\n <p>\"an internal stylesheet is added to the page's <head>\"</p>\n</blockquote>\n\n<p>The theme could be adding in a variety of ways in header.php e.g. hard coding; via a theme \"action hook\"; via wp-head</p>\n\n<p>The last part of header.php typically contains:</p>\n\n<pre><code><?php possibly_themes_own_action_hook(); ?>\n<?php wp_head(); ?>\n</head>\n<body <?php body_class(); ?>>\n Some HTML for header and navigation & other stuff prior to Loop adding say H1 title\n</code></pre>\n\n<p>If theme does not have header.php or it is missing <code></head></code> then relevant code is probably in templates.</p>\n\n<p>In your child header.php <strong>just above <code></head></code></strong> (if not present see below) you could either:</p>\n\n<ul>\n<li>hard code your CSS or stylesheet link above <code></head></code> </li>\n<li><p><strong>or</strong> <code><php include('path/to/mycss.css');?></code></p></li>\n<li><p><strong>or</strong> add your own action:</p>\n\n<pre><code> my_add_to_head(); \n</code></pre>\n\n<p>and in your functions.php</p>\n\n<pre><code> function my_head_function() {\n ?>\n <style>.hero-description {border:1px solid #c00;}</style> \n <?php\n // or stylesheet link or file_get_contents to get css file and echo\n // + any other stuff you want to add to head\n }\n add_action('my_add_to_head', 'my_head_function');\n</code></pre></li>\n</ul>\n\n<p>Solutions are <strong>bad practice</strong> especially if someone else ends up having to maintain but may be the best option with your theme.</p>\n\n<blockquote>\n <p>\"when i used wp_head, it ended up in the tag with all the\n JavaScript files.\"</p>\n</blockquote>\n\n<p>If you mean within the body tag then there is a coding error in the theme. Otherwise it is \"non-standard\" design and could cause many plugins to \"fail\". Either <code>wp_head();</code> is after the body tag or \"wp_head\" is used to insert <code><body></code> and maybe <code></head></code>. </p>\n\n<p>If <code></head></code> is not in header.php or templates then adding the above \"solutions\" just above <code>wp_head();</code> <em>might</em> still work but plugin issues will remain.</p>\n"
}
]
| 2017/06/25 | [
"https://wordpress.stackexchange.com/questions/271295",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122585/"
]
| Let me start by saying I know there are other posts about this, and a lot of documentation is available for this topic, but none of these resources have helped me to solve my issue.
I'm a beginner at creating plugins for WordPress. This is my first, so I'm sure I'm missing something simple, but everything I have read says this should be working.
The plugin activates no problem, my menu shows up, etc. But the following does not create a new table in the database. I removed everything besides the id just to see if it was the SQL syntax, still no results.
```
register_activation_hook( __FILE__, 'pf_rb_install' );
function pf_rb_install() {
global $wpdb;
$table_name = $wpdb->prefix . 'pf_parts';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE '$table_name' (
id mediumint(9) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta( $sql );
}
```
Thanks in advance for any help. | It's not elegant but it works.
Add these lines to functions.php:
```
ob_start();
add_action('shutdown', function() {
$final = '';
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
// append styles just before </head>
$final = str_replace( "</head>", '<link rel="stylesheet" src="mycss.css"></head>', $final );
echo $final;
}, 0);
```
Alternatively you can move all the inline styles at the beginning of the head, better if just after the title tag:
```
ob_start();
add_action('shutdown', function() {
$final = '';
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++) {
$final .= ob_get_clean();
}
/* Adjust the final output */
// load HTML DOM
$dom= new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $final );
// collect styles and remove them from DOM
$inline_styles = "";
$styles = $dom->getElementsByTagName("style");
foreach( $styles as $style )
{
$inline_styles .= $dom->saveHTML( $style );
$style->parentNode->removeChild( $style );
}
$final = $dom->saveHTML();
// strip utf-8 workaround
$final = str_replace( '<?xml encoding="utf-8" ?>', "", $final );
// append styles after <title>
$final = str_replace( "</title>", "</title>\n" . $inline_styles, $final );
echo $final;
}, 0);
``` |
271,296 | <p>I'm trying to format a number in a table cell with comma separators between thousands. The number is coming from a custom field generated in Advanced Custom Fields plugin, where it is required to be a number. </p>
<p>(But I've also tried just entering the number directly in the below examples.)</p>
<p>I'm getting the correct number value, but the formatting isn't working. Plus, I get different results from number_format inside a table cell and outside one.</p>
<p>My number is 429000, retrieved by the_field('price').</p>
<p>Here's what I've tried inside the cell:</p>
<pre><code><td class="pl-property-price"><?php number_format( the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format((int) the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format( intval(the_field('price'))); ?> </td>
<td class="pl-property-price"><?php number_format( the_field('price'), 0, ".", ","); ?> </td>
</code></pre>
<p>and some other variations.</p>
<p>No matter what I do, it outputs 429000 without the comma separator.</p>
<p>Now, if I try to echo the value outside the table, using code like this and all the similar variations to the above using </p>
<pre><code><?php echo number_format(the_field('price')); ?>
</code></pre>
<p>I get 4290000 which adds an extra zero.</p>
<p>I'm puzzled.</p>
| [
{
"answer_id": 271302,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 3,
"selected": true,
"text": "<p>Seems like the function you using is the <a href=\"https://www.advancedcustomfields.com/resources/the_field/\" rel=\"nofollow noreferrer\">the_field</a> function from of <a href=\"https://www.advancedcustomfields.com\" rel=\"nofollow noreferrer\">ACF</a> which is a function that outputs a string so the formatting number_formatt dosent effect the output. </p>\n\n<p>This code: </p>\n\n<pre><code> <?php echo number_format(the_field('price')); ?>\n</code></pre>\n\n<p>The echo does not really print anything, the function the_fields prints the output, that's the reason the number_format function doesn't have any effect on the output. </p>\n\n<p>Try getting the field via different function <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">get_field</a> for example, or you could add the the function the_fields a $format_value argument like you could see in the <a href=\"https://www.advancedcustomfields.com/resources/the_field/\" rel=\"nofollow noreferrer\">docs</a> .</p>\n\n<p>This should work:</p>\n\n<pre><code><?php echo number_format( get_field( 'price' ) ); ?>\n</code></pre>\n"
},
{
"answer_id": 271303,
"author": "Marcos Nakamine",
"author_id": 46049,
"author_profile": "https://wordpress.stackexchange.com/users/46049",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><code>get_field()</code>: Returns the value of a specific field.</li>\n<li><code>the_field()</code>: Displays the value of a specific field.</li>\n</ul>\n\n<p>The correct snippet looks like this:</p>\n\n<pre><code><?php echo number_format( get_field( 'price' ) ); ?>\n</code></pre>\n"
},
{
"answer_id": 271304,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<p>In your case you need to use the <code>get_field</code> function instead of <code>the_field</code>.</p>\n\n<p><code>the_field</code> echos the value, whereas <code>get_field</code> returns a value in which you can pass as the parameter value to the <code>number_format</code>.</p>\n\n<pre><code><?php echo number_format(get_field('price')); ?>\n</code></pre>\n\n<p>You can also learn more about <a href=\"http://php.net/manual/en/function.number-format.php\" rel=\"nofollow noreferrer\">number_format</a></p>\n"
}
]
| 2017/06/25 | [
"https://wordpress.stackexchange.com/questions/271296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41091/"
]
| I'm trying to format a number in a table cell with comma separators between thousands. The number is coming from a custom field generated in Advanced Custom Fields plugin, where it is required to be a number.
(But I've also tried just entering the number directly in the below examples.)
I'm getting the correct number value, but the formatting isn't working. Plus, I get different results from number\_format inside a table cell and outside one.
My number is 429000, retrieved by the\_field('price').
Here's what I've tried inside the cell:
```
<td class="pl-property-price"><?php number_format( the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format((int) the_field('price')); ?> </td>
<td class="pl-property-price"><?php number_format( intval(the_field('price'))); ?> </td>
<td class="pl-property-price"><?php number_format( the_field('price'), 0, ".", ","); ?> </td>
```
and some other variations.
No matter what I do, it outputs 429000 without the comma separator.
Now, if I try to echo the value outside the table, using code like this and all the similar variations to the above using
```
<?php echo number_format(the_field('price')); ?>
```
I get 4290000 which adds an extra zero.
I'm puzzled. | Seems like the function you using is the [the\_field](https://www.advancedcustomfields.com/resources/the_field/) function from of [ACF](https://www.advancedcustomfields.com) which is a function that outputs a string so the formatting number\_formatt dosent effect the output.
This code:
```
<?php echo number_format(the_field('price')); ?>
```
The echo does not really print anything, the function the\_fields prints the output, that's the reason the number\_format function doesn't have any effect on the output.
Try getting the field via different function [get\_field](https://www.advancedcustomfields.com/resources/get_field/) for example, or you could add the the function the\_fields a $format\_value argument like you could see in the [docs](https://www.advancedcustomfields.com/resources/the_field/) .
This should work:
```
<?php echo number_format( get_field( 'price' ) ); ?>
``` |
271,322 | <p>I'm trying to create a custom WordPress theme from scratch. As you can see, my file structure looks like this - footer.php, header.php, index.php, about.php, and contact.php within my theme folder:</p>
<p><a href="https://i.stack.imgur.com/zLjPX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zLjPX.png" alt="enter image description here"></a></p>
<p>I've completed the home page (index.php) and now I'm trying to create these other pages and link to them. But when I go to these pages from the <a href="http://new.gatewaywebdesign.com/" rel="nofollow noreferrer">home page</a>, the only way that I could get them to link was through this long, ugly link structure:</p>
<p><a href="https://i.stack.imgur.com/ZSlEo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZSlEo.png" alt="enter image description here"></a></p>
<p>I'm wondering if I've gone about this the wrong way. If I create the new pages in WordPress instead of manually via FTP, will this allow me to change the permalink structure so that I can have <code>new.gatewaywebdesign.com/contact.php</code> instead of <code>new.gatewaywebdesign.com/wp-content/themes/gatewaywebdesign/contact.php</code>? </p>
<p>I went ahead and tried to create a <code>contact</code> page in the WordPress dashboard but it won't let me get rid of <code>index.php</code> after the site name:</p>
<p><a href="https://i.stack.imgur.com/EKsEZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EKsEZ.png" alt="enter image description here"></a></p>
<p>Any other suggestions for editing / trimming link structure? Thanks</p>
| [
{
"answer_id": 271324,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Theme PHP files never get linked to or loaded directly. You create pages via the admin interface, whose content lives in the database, and WordPress maps incoming requests to the appropriate theme file based on the type of request- home, archive, single post, single page, etc.. Have a look at the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">Template Hierarchy</a> for more info on which theme files get used for each type of request.</p>\n\n<p>The issue of <code>index.php</code> appearing in permalinks is separate. You typically need a server that has <code>mod_rewrite</code> enabled for full \"Pretty\" Permalinks. Right now you've got what's known as PATHINFO, or \"Almost Pretty\" permalinks. Have a read through the <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">Using Permalinks</a> page for more info on the requirements for each.</p>\n"
},
{
"answer_id": 271325,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>As @Milo mentioned in his answer, you can't and shouldn't directly call a template file. It is a security risk, and you will no longer be able to access WordPress's engine, so you can't use functions such as <code>the_permalink</code>.</p>\n\n<p>To include a template part in your <code>home.php</code> or any where you wish, you can use <code>get_template_part()</code>:</p>\n\n<pre><code>get_template_part( 'relative/path/to/template' );\n</code></pre>\n\n<p>Don't include <code>.php</code>. It will be added automatically. So, if your <code>about.php</code> is inside <code>/theme/my-theme/folder/</code>, and your <code>home.php</code> is in <code>/theme/my-theme/</code>, you should use this function the following way:</p>\n\n<pre><code>get_template_part( 'folder/about' );\n</code></pre>\n\n<p>That will include <code>about.php</code> wherever you use the code. Now you have full access to WordPress inside your <code>about.php</code> and there is no need of any ugly URL.</p>\n\n<h2>UPDATE</h2>\n\n<p>To add a page, create a blank php file named <code>page-whatever.php</code>. Then add the following to its header:</p>\n\n<pre><code><?php \n/**\n * This is the template for Pages\n *\n * @package YourPackage\n */\n\nget_header();\n\nget_template_part('path/to/portfolio');\n</code></pre>\n\n<p>Now, you can see your new page template in the back end, while adding a page (under page template drop-down menu).</p>\n"
},
{
"answer_id": 271340,
"author": "KazeZlat",
"author_id": 122604,
"author_profile": "https://wordpress.stackexchange.com/users/122604",
"pm_score": 1,
"selected": false,
"text": "<p>If what you want is to have different template on <code>//site.com/contact/</code> then you need to create a page, set this permalink to it and create template file called <code>page-contact.php</code>.</p>\n\n<p>That is how WP works:</p>\n\n<ol>\n<li><p>Search for specific template (such as our <code>page-contact.php</code>)</p></li>\n<li><p>Search for generic template (e.g. <code>page.php</code>, <code>single.php</code> and so on) </p></li>\n<li><p>Use <code>index.php</code></p></li>\n</ol>\n\n<p>So if it can't find 1st it goes to 2nd and then falls to <code>index.php</code>. Just take a look at <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#examples\" rel=\"nofollow noreferrer\">how WP template hierarchy built</a></p>\n"
},
{
"answer_id": 272253,
"author": "HappyHands31",
"author_id": 116029,
"author_profile": "https://wordpress.stackexchange.com/users/116029",
"pm_score": 1,
"selected": true,
"text": "<p>The answer to this question is yes, creating the pages in WordPress does allow you to change the link structure. What I needed to do was rework <code>index.php</code> so that it used the <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">WordPress Loop</a>, and then displayed the front page as whatever the front page was set to in the WordPress dashboard. So my <code>index.php</code> ended up looking like this:</p>\n\n<pre><code><?php get_header();?>\n\n<?php if ( have_posts() ) : ?>\n\n// Set front page\n<?php if ( is_home() && ! is_front_page() ) : ?>\n// Display page title\n<header>\n<h1 class=\"page-title screen-reader-text\"><?php single_post_title(); ?></h1>\n</header>\n<?php endif; ?>\n\n<?php\n// Start the loop.\nwhile ( have_posts() ) : the_post();\n\n/*\n* Include the Post-Format-specific template for the content.\n* If you want to override this in a child theme, then include a file\n* called content-___.php (where ___ is the Post Format name) and that will be used instead.\n*/\nget_template_part( 'content', get_post_format() );\n\n// End the loop.\nendwhile;\n\n// Previous/next page navigation.\n/* the_posts_pagination( array(\n'prev_text' => __( 'Previous page', 'twentyfifteen' ),\n'next_text' => __( 'Next page', 'twentyfifteen' ),\n'before_page_number' => '<span class=\"meta-nav screen-reader-text\">' . __( 'Page', 'twentyfifteen' ) . ' </span>',\n) );*/\n\n// If no content, include the \"No posts found\" template.\nelse :\nget_template_part( 'content', 'none' );\n\nendif;\n?>\n\n<?php get_footer();?>\n</code></pre>\n\n<p>Make sure that your theme has all the necessary core files - <code>single.php</code>, <code>content-link.php</code>, <code>content-none.php</code>, <code>content-page.php</code>, <code>content-search.php</code>, <code>content.php</code>, and <code>page.php</code>. </p>\n\n<p>Then in WordPress, create a menu and set the pages that you've created in WordPress to be in that menu. </p>\n\n<p>In <code>header.php</code>, set the links to the different pages in your nav menu like this:</p>\n\n<pre><code><div class=\"menu-container\"><!--menu items-->\n<?php $main_menu = inits_get_main_menu();\n foreach ($main_menu as $menu) { //var_dump( $menu); exit; ?>\n <div class=\"menu-item contact\">\n <a class=\"menu-link\" href=\"<?php echo $menu->url; ?>\">\n <?php echo $menu->title; ?>\n </a>\n </div>\n<?php } ?>\n</div>\n</code></pre>\n\n<p>Now your menu has been set in the header, and when you click on one of the links to your other pages, the link structure will look the way that you want it to. </p>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271322",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116029/"
]
| I'm trying to create a custom WordPress theme from scratch. As you can see, my file structure looks like this - footer.php, header.php, index.php, about.php, and contact.php within my theme folder:
[](https://i.stack.imgur.com/zLjPX.png)
I've completed the home page (index.php) and now I'm trying to create these other pages and link to them. But when I go to these pages from the [home page](http://new.gatewaywebdesign.com/), the only way that I could get them to link was through this long, ugly link structure:
[](https://i.stack.imgur.com/ZSlEo.png)
I'm wondering if I've gone about this the wrong way. If I create the new pages in WordPress instead of manually via FTP, will this allow me to change the permalink structure so that I can have `new.gatewaywebdesign.com/contact.php` instead of `new.gatewaywebdesign.com/wp-content/themes/gatewaywebdesign/contact.php`?
I went ahead and tried to create a `contact` page in the WordPress dashboard but it won't let me get rid of `index.php` after the site name:
[](https://i.stack.imgur.com/EKsEZ.png)
Any other suggestions for editing / trimming link structure? Thanks | The answer to this question is yes, creating the pages in WordPress does allow you to change the link structure. What I needed to do was rework `index.php` so that it used the [WordPress Loop](https://codex.wordpress.org/The_Loop), and then displayed the front page as whatever the front page was set to in the WordPress dashboard. So my `index.php` ended up looking like this:
```
<?php get_header();?>
<?php if ( have_posts() ) : ?>
// Set front page
<?php if ( is_home() && ! is_front_page() ) : ?>
// Display page title
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php endif; ?>
<?php
// Start the loop.
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
// End the loop.
endwhile;
// Previous/next page navigation.
/* the_posts_pagination( array(
'prev_text' => __( 'Previous page', 'twentyfifteen' ),
'next_text' => __( 'Next page', 'twentyfifteen' ),
'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentyfifteen' ) . ' </span>',
) );*/
// If no content, include the "No posts found" template.
else :
get_template_part( 'content', 'none' );
endif;
?>
<?php get_footer();?>
```
Make sure that your theme has all the necessary core files - `single.php`, `content-link.php`, `content-none.php`, `content-page.php`, `content-search.php`, `content.php`, and `page.php`.
Then in WordPress, create a menu and set the pages that you've created in WordPress to be in that menu.
In `header.php`, set the links to the different pages in your nav menu like this:
```
<div class="menu-container"><!--menu items-->
<?php $main_menu = inits_get_main_menu();
foreach ($main_menu as $menu) { //var_dump( $menu); exit; ?>
<div class="menu-item contact">
<a class="menu-link" href="<?php echo $menu->url; ?>">
<?php echo $menu->title; ?>
</a>
</div>
<?php } ?>
</div>
```
Now your menu has been set in the header, and when you click on one of the links to your other pages, the link structure will look the way that you want it to. |
271,327 | <p>I manage a Wordpress site. The regular site (outside the admin login) is normal, but when I went to log in to the admin panel today, and got this brute force protection screen: <a href="https://i.stack.imgur.com/7Q2LP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Q2LP.png" alt="brute force prevention screen"></a></p>
<p>I don't have any brute force protection plugins installed, and I've never seen this screen before, so I'm concerned that this is a hack of some kind. The source of the page is this:</p>
<pre><code><html>
<head>
<title>Wordpress Anti Bruteforce</title>
<style type="text/css">
.center {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.button-container {
margin-top: 30px;
}
.text {
margin-top: 30px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
.button-container {
padding-top: 10px;
}
.button {
font-size: 20px;
height: 50px;
width: 300px;
}
#logo {
width: 540px;
height: 122px;
background: url('...')
/* removed this for brevity - contains a Wordpress logo in svg as a data: url */
}
</style>
</head>
<body>
<div class="center">
<div id="logo"></div>
<h4 class="text">Please click the Login button to confirm you aren't a bot.</h4>
<div class="button-container">
<input type="button" class="button" onclick="_login()" value="Login to Wordpress" />
</div>
</div>
<script language="javascript">
function _login() {
document.cookie = "antibot=* 15 character alphanumeric code here *; expires=Thu, 18 Dec 2026 12:00:00 UTC; path=/";
location.reload();
}
</script>
</body>
</code></pre>
<p>Is this likely a hack, or should I just go ahead and click the button? The plugins I have installed are <a href="https://wordpress.org/plugins/contact-form-7/" rel="nofollow noreferrer">Contact Form 7</a>, <a href="https://wordpress.org/plugins/the-events-calendar/" rel="nofollow noreferrer">The Events Calendar</a>, and <a href="https://wordpress.org/plugins/wp-miniaudioplayer/" rel="nofollow noreferrer">mb.miniAudioPlayer</a>.</p>
| [
{
"answer_id": 271329,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Do you have JetPack activated? It has some brute-force capabilities. </p>\n\n<p>I'd also suggest looking at the wp-login.php code (via your file manager) to see if it has changed. Look for dates different than the rest of them.</p>\n\n<p>You could also reinstall the WP software manually.</p>\n\n<p>The code will reload the current page - I'm assuming it is the wp-login.php page. That's why you need to check that pages' code....to see if it has changed.</p>\n\n<p>By itself, the code you posted is benign. Except for the part where it reloads the current page, which might be 'bad'.</p>\n"
},
{
"answer_id": 271336,
"author": "hwl",
"author_id": 118366,
"author_profile": "https://wordpress.stackexchange.com/users/118366",
"pm_score": 0,
"selected": false,
"text": "<p>1) No, <a href=\"https://wordpress.org/support/topic/built-in-brute-force-protection/\" rel=\"nofollow noreferrer\">WP does not have built in brute force prevention</a>, though such protection <a href=\"https://codex.wordpress.org/Brute_Force_Attacks\" rel=\"nofollow noreferrer\">should be considered</a>. </p>\n\n<p>2) Keep in mind, this could be something a theme has installed as well, or a must-use plugin from the hosting provider. </p>\n\n<p>3) That said, <a href=\"https://www.w3.org/TR/SVGTiny12/mimereg.html\" rel=\"nofollow noreferrer\">SVGs have some security issues</a>, so being sure that's an unaltered WP svg file would be good to know. Here is a good read on why they are <a href=\"https://www.bjornjohansen.no/svg-in-wordpress\" rel=\"nofollow noreferrer\">omitted from WP media uploader for that reason</a>.</p>\n\n<hr>\n\n<p>In addition to checking wp-login.php as mentioned by <a href=\"https://wordpress.stackexchange.com/users/29416/rick-hellewell\">Rick</a>, inspect both the theme's functions.php and the directory structure in general. A search for the following strings may help pinpoint files:</p>\n\n<pre><code> add_action( 'login_form, \n add_action( 'login_footer \n add_filter( 'login_headerurl, \n add_filter( 'login_headertitle, \n add_filter( 'login_message, \n add_filter( 'login_errors \n add_action( 'login_enqueue_scripts, \n add_action( 'login_head.\n</code></pre>\n\n<hr>\n\n<p>If you want to check the DB for plugins, they are saved in </p>\n\n<pre><code>(table) <prefix>_options \n (row) option_name\n active_plugins \n</code></pre>\n\n<p>If you have db access, you can disable all plugins with the following SQL:\n<code>UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';\n</code> \n<a href=\"https://perishablepress.com/quickly-disable-or-enable-all-wordpress-plugins-via-the-database/\" rel=\"nofollow noreferrer\">Source and more info on SQL</a></p>\n"
},
{
"answer_id": 310343,
"author": "Ciprian",
"author_id": 7349,
"author_profile": "https://wordpress.stackexchange.com/users/7349",
"pm_score": 2,
"selected": true,
"text": "<p>It looks like a poorly coded hosting-side protection.</p>\n\n<p>I say poorly coded because \"Wordpress\" is misspelled and it uses <code><script language=\"javascript\"></code>.</p>\n\n<p>Ask your host. This is definitely not WordPress native behaviour.</p>\n\n<p>Also, check your document root, as the file seems to be self-contained. It might be an extra HTML file in your document root. Use your hosting panel File Manager, or an (S)FTP app, such as WinSCP or FileZilla.</p>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122594/"
]
| I manage a Wordpress site. The regular site (outside the admin login) is normal, but when I went to log in to the admin panel today, and got this brute force protection screen: [](https://i.stack.imgur.com/7Q2LP.png)
I don't have any brute force protection plugins installed, and I've never seen this screen before, so I'm concerned that this is a hack of some kind. The source of the page is this:
```
<html>
<head>
<title>Wordpress Anti Bruteforce</title>
<style type="text/css">
.center {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.button-container {
margin-top: 30px;
}
.text {
margin-top: 30px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
.button-container {
padding-top: 10px;
}
.button {
font-size: 20px;
height: 50px;
width: 300px;
}
#logo {
width: 540px;
height: 122px;
background: url('...')
/* removed this for brevity - contains a Wordpress logo in svg as a data: url */
}
</style>
</head>
<body>
<div class="center">
<div id="logo"></div>
<h4 class="text">Please click the Login button to confirm you aren't a bot.</h4>
<div class="button-container">
<input type="button" class="button" onclick="_login()" value="Login to Wordpress" />
</div>
</div>
<script language="javascript">
function _login() {
document.cookie = "antibot=* 15 character alphanumeric code here *; expires=Thu, 18 Dec 2026 12:00:00 UTC; path=/";
location.reload();
}
</script>
</body>
```
Is this likely a hack, or should I just go ahead and click the button? The plugins I have installed are [Contact Form 7](https://wordpress.org/plugins/contact-form-7/), [The Events Calendar](https://wordpress.org/plugins/the-events-calendar/), and [mb.miniAudioPlayer](https://wordpress.org/plugins/wp-miniaudioplayer/). | It looks like a poorly coded hosting-side protection.
I say poorly coded because "Wordpress" is misspelled and it uses `<script language="javascript">`.
Ask your host. This is definitely not WordPress native behaviour.
Also, check your document root, as the file seems to be self-contained. It might be an extra HTML file in your document root. Use your hosting panel File Manager, or an (S)FTP app, such as WinSCP or FileZilla. |
271,338 | <p>I've been trying to achieve a seemingly simple permalink structure customization without success. The goal is to always have <code>/aa-bb/</code> in front of each possible permalink, where aa is a language code and bb a country code. Whatever comes after this should behave exactly like it would normally. So where normally you'd have <code>/post-title/</code>, afterwards you'd have <code>/en-gb/post-title/</code> and it would lead to the same post (including all variations such as pages, CPTs, archives, categories, search etc.).</p>
<p><strong>The complete flow:</strong></p>
<ol>
<li>I generate a list of valid language/country values = <em>complete</em></li>
<li>I retrieve the value from the URL to determine the language/country = <em>complete</em></li>
<li>During the template_redirect action hook I redirect to the default language/country if no valid value is present = <em>complete</em></li>
<li>Set up a permalink rewrite structure to process these URLs as if the first part didn't exist = <em>mystery</em></li>
</ol>
<p>All methods for rewriting WP permalinks seem to do something slightly different from this goal. Is this something that would be better done with htaccess? WPML seems to do it successfully with their language codes but I'm not sure how.</p>
<p>Using add_rewrite_rule sure works, but only covers one permalink type at a time so I'm afraid of falling short if I'd manually add all variations.</p>
| [
{
"answer_id": 271343,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that you could use <a href=\"https://wordpress.org/plugins/polylang/\" rel=\"nofollow noreferrer\">polylang plugin</a>. I made one of my project like you mentioned with that plugin.</p>\n"
},
{
"answer_id": 271347,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 4,
"selected": true,
"text": "<p>I'm working on a similar solution right now - the website must have language codes in all URLs (except the default language), but only pages are translatable in a way WPML/Polylang plugins do it. For news (blog) we just show posts in particular language (they are separate, not translations of each other). All the other content is mixed in all languages. Also, the UI is displayed in a language set from URL too.</p>\n\n<p>Here's what I did to get those rewrite rules prepended with language codes:</p>\n\n<pre><code>function prepend_default_rewrite_rules( $rules ) {\n\n // Prepare for new rules\n $new_rules = [];\n\n // Set up languages, except default one\n $language_slugs = ['ar', 'ku'];\n\n // Generate language slug regex\n $languages_slug = '(?:' . implode( '/|', $language_slugs ) . '/)?';\n\n\n // Set up the list of rules that don't need to be prefixed\n $whitelist = [\n '^wp-json/?$',\n '^wp-json/(.*)?',\n '^index.php/wp-json/?$',\n '^index.php/wp-json/(.*)?'\n ];\n\n // Set up the new rule for home page\n $new_rules['(?:' . implode( '/|', $language_slugs ) . ')/?$'] = 'index.php';\n\n // Loop through old rules and modify them\n foreach ( $rules as $key => $rule ) {\n\n // Re-add those whitelisted rules without modification\n if ( in_array( $key, $whitelist ) ) {\n\n $new_rules[ $key ] = $rule;\n\n // Update rules starting with ^ symbol\n } elseif ( substr( $key, 0, 1 ) === '^' ) { \n\n $new_rules[ $languages_slug . substr( $key, 1 ) ] = $rule;\n\n\n // Update other rules\n } else {\n\n $new_rules[ $languages_slug . $key ] = $rule;\n\n }\n }\n\n\n // Return out new rules\n return $new_rules;\n}\nadd_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' );\n</code></pre>\n\n<p>Haven't tested it to full extent - just came up with the solution after studying the WP_Rewrite class. So it's a work in progress. Hope it helps though.</p>\n\n<p>P.S.: Also, I would be happy to see your solution for \"I retrieve the value from the URL to determine the language/country = complete\" - that's what I'm currently working on :)</p>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20044/"
]
| I've been trying to achieve a seemingly simple permalink structure customization without success. The goal is to always have `/aa-bb/` in front of each possible permalink, where aa is a language code and bb a country code. Whatever comes after this should behave exactly like it would normally. So where normally you'd have `/post-title/`, afterwards you'd have `/en-gb/post-title/` and it would lead to the same post (including all variations such as pages, CPTs, archives, categories, search etc.).
**The complete flow:**
1. I generate a list of valid language/country values = *complete*
2. I retrieve the value from the URL to determine the language/country = *complete*
3. During the template\_redirect action hook I redirect to the default language/country if no valid value is present = *complete*
4. Set up a permalink rewrite structure to process these URLs as if the first part didn't exist = *mystery*
All methods for rewriting WP permalinks seem to do something slightly different from this goal. Is this something that would be better done with htaccess? WPML seems to do it successfully with their language codes but I'm not sure how.
Using add\_rewrite\_rule sure works, but only covers one permalink type at a time so I'm afraid of falling short if I'd manually add all variations. | I'm working on a similar solution right now - the website must have language codes in all URLs (except the default language), but only pages are translatable in a way WPML/Polylang plugins do it. For news (blog) we just show posts in particular language (they are separate, not translations of each other). All the other content is mixed in all languages. Also, the UI is displayed in a language set from URL too.
Here's what I did to get those rewrite rules prepended with language codes:
```
function prepend_default_rewrite_rules( $rules ) {
// Prepare for new rules
$new_rules = [];
// Set up languages, except default one
$language_slugs = ['ar', 'ku'];
// Generate language slug regex
$languages_slug = '(?:' . implode( '/|', $language_slugs ) . '/)?';
// Set up the list of rules that don't need to be prefixed
$whitelist = [
'^wp-json/?$',
'^wp-json/(.*)?',
'^index.php/wp-json/?$',
'^index.php/wp-json/(.*)?'
];
// Set up the new rule for home page
$new_rules['(?:' . implode( '/|', $language_slugs ) . ')/?$'] = 'index.php';
// Loop through old rules and modify them
foreach ( $rules as $key => $rule ) {
// Re-add those whitelisted rules without modification
if ( in_array( $key, $whitelist ) ) {
$new_rules[ $key ] = $rule;
// Update rules starting with ^ symbol
} elseif ( substr( $key, 0, 1 ) === '^' ) {
$new_rules[ $languages_slug . substr( $key, 1 ) ] = $rule;
// Update other rules
} else {
$new_rules[ $languages_slug . $key ] = $rule;
}
}
// Return out new rules
return $new_rules;
}
add_filter( 'rewrite_rules_array', 'prepend_default_rewrite_rules' );
```
Haven't tested it to full extent - just came up with the solution after studying the WP\_Rewrite class. So it's a work in progress. Hope it helps though.
P.S.: Also, I would be happy to see your solution for "I retrieve the value from the URL to determine the language/country = complete" - that's what I'm currently working on :) |
271,341 | <p>I am trying to Auto update the woocommerce cart after quantity is changed. The following code within the function.php is working, BUT updates the cart only if I change the quantity twice. Do you know how to fix that?</p>
<pre><code>add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
if (is_cart()) :
?>
<script>
jQuery('div.woocommerce').on('change', '.qty', function(){
jQuery("[name='update_cart']").trigger("click");
});
</script>
<?php
endif;
}
</code></pre>
| [
{
"answer_id": 271369,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>Your above code works pretty well in my local system. Don't know why its not working on your system. But you can try writing the <strong><em>JS</em></strong> code like below-</p>\n\n<pre><code>add_action( 'wp_footer', 'cart_update_qty_script' );\nfunction cart_update_qty_script() {\n if (is_cart()) :\n ?>\n <script type=\"text/javascript\">\n (function($){\n $(function(){\n $('div.woocommerce').on( 'change', '.qty', function(){\n $(\"[name='update_cart']\").trigger('click');\n });\n });\n })(jQuery);\n </script>\n <?php\n endif;\n}\n</code></pre>\n\n<p>It's more precise approach and cleaner I think. </p>\n\n<p>Hope the above thing helps.</p>\n"
},
{
"answer_id": 304327,
"author": "heraphim",
"author_id": 144194,
"author_profile": "https://wordpress.stackexchange.com/users/144194",
"pm_score": 4,
"selected": true,
"text": "<p>Almost one year late, but this question might still get visitors:\nYou trigger the click, but the button doesn't have enough time to become enabled, so that is why, by the time you click the second time the button becomes enabled. Remove the \"disabled\" propriety before triggering the click:</p>\n\n<pre><code> <script>\n jQuery('div.woocommerce').on('change', '.qty', function(){\n jQuery(\"[name='update_cart']\").prop(\"disabled\", false);\n jQuery(\"[name='update_cart']\").trigger(\"click\"); \n });\n </script>\n</code></pre>\n"
},
{
"answer_id": 337678,
"author": "Ryszard Jędraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 0,
"selected": false,
"text": "<p>I created a free plugin <a href=\"https://wordpress.org/plugins/ajax-cart-autoupdate-for-woocommerce/#description\" rel=\"nofollow noreferrer\">Ajax Cart AutoUpdate</a> to update cart page and mini cart totals on product quantity change. It has nice additional options, but also script alone provides wider browser support and much better user experience.</p>\n\n<p>Ajax calls aren't constantly sent due to introduced update delay, in provided example it's 1000 miliseconds, but actual plugin code uses value specified in settings. It works like this:</p>\n\n<p>\"Cart update is delayed by amount in miliseconds since last action affecting quantity, specified by user in settings, default 1000. It means that update will fire only once, when user is done with changes.\"</p>\n\n<p>Also for page speed fanatics, remember that if you want to defer jQuery, you better load scripts using <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a>, with jQuery dependency set, because inline script with jQuery will fail in such case.</p>\n\n<pre><code>var timeout;\n\njQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support\n if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event\n if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing\n timeout = setTimeout(function() {\n jQuery('[name=\"update_cart\"]').trigger('click');\n }, 1000 ); // schedule update cart event with 1000 miliseconds delay\n});\n</code></pre>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271341",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122426/"
]
| I am trying to Auto update the woocommerce cart after quantity is changed. The following code within the function.php is working, BUT updates the cart only if I change the quantity twice. Do you know how to fix that?
```
add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
if (is_cart()) :
?>
<script>
jQuery('div.woocommerce').on('change', '.qty', function(){
jQuery("[name='update_cart']").trigger("click");
});
</script>
<?php
endif;
}
``` | Almost one year late, but this question might still get visitors:
You trigger the click, but the button doesn't have enough time to become enabled, so that is why, by the time you click the second time the button becomes enabled. Remove the "disabled" propriety before triggering the click:
```
<script>
jQuery('div.woocommerce').on('change', '.qty', function(){
jQuery("[name='update_cart']").prop("disabled", false);
jQuery("[name='update_cart']").trigger("click");
});
</script>
``` |
271,350 | <p>When trashing a post, also trash related comments
so here is what i want, what‘s’ the sql Command</p>
<p>I want to move some post to trash according their ID, what is the sql command,I can restore these post and their comments using sql command</p>
| [
{
"answer_id": 271354,
"author": "Picard",
"author_id": 118566,
"author_profile": "https://wordpress.stackexchange.com/users/118566",
"pm_score": 2,
"selected": false,
"text": "<p>I would discourage using raw SQL for moving a post to a trash or back, especially since there's a build in function for it:</p>\n\n<pre><code>wp_trash_post( $post_id ); \n</code></pre>\n\n<p>More about the <a href=\"https://codex.wordpress.org/Function_Reference/wp_trash_post\" rel=\"nofollow noreferrer\">wp_trash_post()</a> function.</p>\n\n<p>The opposite is:</p>\n\n<pre><code>wp_untrash_post( $post_id );\n</code></pre>\n\n<p><code>wp_untrash_post()</code> also untrashes trashed comments.</p>\n\n<p>In WP there are functions for many things - for instance you can trash/untrash only comments, leaving the post alone - in that case use: <code>wp_untrash_post_comments()</code> and <code>wp_trash_post_comments()</code>.</p>\n"
},
{
"answer_id": 271405,
"author": "Biswa Bandhu Bhandary",
"author_id": 119082,
"author_profile": "https://wordpress.stackexchange.com/users/119082",
"pm_score": 0,
"selected": false,
"text": "<p>Sql Command for trashed a post with comments for that post:</p>\n\n<pre><code>$post_status = 'trash';\n$post_array = '1, 2, 3'; //post_ids comma separated\n\n$wpdb->query($wpdb->prepare( \n \"UPDATE \n `wp_posts`, \n `wp_comments` \n SET \n wp_posts.post_status= %s, \n wp_comments.comment_approved= %s \n WHERE \n wp_posts.ID = wp_comments.comment_post_ID AND \n wp_posts.ID IN ( $post_array )\", \n $post_status,\n $post_status \n));\n</code></pre>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271350",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122605/"
]
| When trashing a post, also trash related comments
so here is what i want, what‘s’ the sql Command
I want to move some post to trash according their ID, what is the sql command,I can restore these post and their comments using sql command | I would discourage using raw SQL for moving a post to a trash or back, especially since there's a build in function for it:
```
wp_trash_post( $post_id );
```
More about the [wp\_trash\_post()](https://codex.wordpress.org/Function_Reference/wp_trash_post) function.
The opposite is:
```
wp_untrash_post( $post_id );
```
`wp_untrash_post()` also untrashes trashed comments.
In WP there are functions for many things - for instance you can trash/untrash only comments, leaving the post alone - in that case use: `wp_untrash_post_comments()` and `wp_trash_post_comments()`. |
271,375 | <p>I have created a custom post type called 'articles' with all the same capabilities as the general post type & I am using the same template to display both archives. </p>
<p>The blog page that uses the built in posts shows posted on and by, </p>
<p><a href="http://madebyfactory.com/backstage/" rel="nofollow noreferrer">Seen here</a></p>
<p>The custom post type page omits this info</p>
<p><a href="http://andonettes-macbook-pro.local:5757/articles/" rel="nofollow noreferrer">Seen here</a></p>
<p>I am lost at this point and don't know what I need to do that's extra, since its using the same code to display both pages. </p>
<p>This is post type function: </p>
<pre><code>function post_type_articles() {
$labels = array(
'name' => _x( 'Articles', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Article', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Articles', 'text_domain' ),
'name_admin_bar' => __( 'Article', 'text_domain' ),
'archives' => __( 'Article Archives', 'text_domain' ),
'attributes' => __( 'Article Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Article', 'text_domain' ),
'all_items' => __( 'All Articles', 'text_domain' ),
'add_new_item' => __( 'Add New Article', 'text_domain' ),
'add_new' => __( 'Add New Article', 'text_domain' ),
'new_item' => __( 'New Article', 'text_domain' ),
'edit_item' => __( 'Edit Article', 'text_domain' ),
'update_item' => __( 'Update Article', 'text_domain' ),
'view_item' => __( 'View Article', 'text_domain' ),
'view_items' => __( 'View Article', 'text_domain' ),
'search_items' => __( 'Search Articles', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into article', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this article', 'text_domain' ),
'items_list' => __( 'Articles list', 'text_domain' ),
'items_list_navigation' => __( 'Articles list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter articles list', 'text_domain' ),
);
$args = array(
'label' => __( 'Article', 'text_domain' ),
'description' => __( 'Article Description', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'trackbacks', 'revisions', 'custom-fields', 'page-attributes', 'post-formats', ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'rewrite' => array( 'slug' => 'articles' ),
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-aside',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => 'articles',
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'articles', $args );
</code></pre>
<p>}
add_action( 'init', 'post_type_articles', 0 );</p>
<p>and here is the loop </p>
<pre><code><header class="entry-header">
<?php
if ( is_singular() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title archive-header"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<div class="entry-meta">
<?php factorypress_posted_on(); ?>
</div><!-- .entry-meta -->
<?php
endif; ?>
</header><!-- .entry-header -->
<div class="entry-content">
<div class="row">
<div class="col-sm-3">
<?php the_post_thumbnail('large', array('class' => 'img-responsive')); ?>
</div><!-- /.col-sm-2 -->
<div class="col-sm-9">
<?php
the_content( 'more', sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'factorypress' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
) );
wp_link_pages( array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'factorypress' ),
'after' => '</div>',
) );
?>
</div><!-- /.col-sm-10 -->
</div><!-- /.row -->
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php factorypress_entry_footer(); ?>
</footer><!-- .entry-footer -->
</code></pre>
<p> </p>
<p>Thanks in advance if you can answer this for me!</p>
| [
{
"answer_id": 271377,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<p>This specific line in your code prevents the execution of the <code>factorypress_posted_on</code> method that displays the post metadata.</p>\n\n<pre><code>if ( 'post' === get_post_type() ) : ?>\n</code></pre>\n\n<p>That only validates if the post type is <strong>post</strong> not your custom post type <strong>articles</strong>. I think you should replace that particular line of code with this one:</p>\n\n<pre><code>if ( 'post' === get_post_type() || 'articles' === get_post_type()) : ?>\n</code></pre>\n"
},
{
"answer_id": 271381,
"author": "erichmond",
"author_id": 31057,
"author_profile": "https://wordpress.stackexchange.com/users/31057",
"pm_score": 1,
"selected": true,
"text": "<p>If you're using a custom archive template I think you should add the conditional is_post_type_archive()</p>\n\n<pre><code>if ( 'post' === get_post_type() || is_post_type_archive( array( 'articles' ) ) );\n</code></pre>\n"
},
{
"answer_id": 384002,
"author": "David",
"author_id": 108220,
"author_profile": "https://wordpress.stackexchange.com/users/108220",
"pm_score": 1,
"selected": false,
"text": "<p>In Twenty Twenty One Theme we can find in inc/template-tags.php:</p>\n<pre><code>// Early exit if not a post.\nif ( 'post' !== get_post_type() ) {\n return;\n}\n</code></pre>\n<p>We can override the file to change that code block to:</p>\n<pre><code>// Early exit if not a post or article.\nif ( 'post' !== get_post_type() && 'articles' !== get_post_type() ) {\n return;\n}\n</code></pre>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114456/"
]
| I have created a custom post type called 'articles' with all the same capabilities as the general post type & I am using the same template to display both archives.
The blog page that uses the built in posts shows posted on and by,
[Seen here](http://madebyfactory.com/backstage/)
The custom post type page omits this info
[Seen here](http://andonettes-macbook-pro.local:5757/articles/)
I am lost at this point and don't know what I need to do that's extra, since its using the same code to display both pages.
This is post type function:
```
function post_type_articles() {
$labels = array(
'name' => _x( 'Articles', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Article', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Articles', 'text_domain' ),
'name_admin_bar' => __( 'Article', 'text_domain' ),
'archives' => __( 'Article Archives', 'text_domain' ),
'attributes' => __( 'Article Attributes', 'text_domain' ),
'parent_item_colon' => __( 'Parent Article', 'text_domain' ),
'all_items' => __( 'All Articles', 'text_domain' ),
'add_new_item' => __( 'Add New Article', 'text_domain' ),
'add_new' => __( 'Add New Article', 'text_domain' ),
'new_item' => __( 'New Article', 'text_domain' ),
'edit_item' => __( 'Edit Article', 'text_domain' ),
'update_item' => __( 'Update Article', 'text_domain' ),
'view_item' => __( 'View Article', 'text_domain' ),
'view_items' => __( 'View Article', 'text_domain' ),
'search_items' => __( 'Search Articles', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into article', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this article', 'text_domain' ),
'items_list' => __( 'Articles list', 'text_domain' ),
'items_list_navigation' => __( 'Articles list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter articles list', 'text_domain' ),
);
$args = array(
'label' => __( 'Article', 'text_domain' ),
'description' => __( 'Article Description', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'trackbacks', 'revisions', 'custom-fields', 'page-attributes', 'post-formats', ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'rewrite' => array( 'slug' => 'articles' ),
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-aside',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => 'articles',
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'post',
);
register_post_type( 'articles', $args );
```
}
add\_action( 'init', 'post\_type\_articles', 0 );
and here is the loop
```
<header class="entry-header">
<?php
if ( is_singular() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title archive-header"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<div class="entry-meta">
<?php factorypress_posted_on(); ?>
</div><!-- .entry-meta -->
<?php
endif; ?>
</header><!-- .entry-header -->
<div class="entry-content">
<div class="row">
<div class="col-sm-3">
<?php the_post_thumbnail('large', array('class' => 'img-responsive')); ?>
</div><!-- /.col-sm-2 -->
<div class="col-sm-9">
<?php
the_content( 'more', sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'factorypress' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
) );
wp_link_pages( array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'factorypress' ),
'after' => '</div>',
) );
?>
</div><!-- /.col-sm-10 -->
</div><!-- /.row -->
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php factorypress_entry_footer(); ?>
</footer><!-- .entry-footer -->
```
Thanks in advance if you can answer this for me! | If you're using a custom archive template I think you should add the conditional is\_post\_type\_archive()
```
if ( 'post' === get_post_type() || is_post_type_archive( array( 'articles' ) ) );
``` |
271,425 | <p>I am experimenting creating a WordPress plugin using create-react-app. To make things simple, I am trying to develop a click-to-tweet plugin.</p>
<p>The shortcode part (in PHP ) looks like:</p>
<pre><code>// Shortcode to output needed markup
add_shortcode( 'react_click_to_tweet', 'react_click_to_tweet_test' );
function react_click_to_tweet_test($atts = [], $content = null, $tag = '') {
return '<div id="root" data=' . $content . '></div>';
}
function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_enqueue_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
</code></pre>
<p>$content should be the text to tweet that I want to pass with the shortcode as:</p>
<pre><code>[react_click_to_tweet]TEXT TO TWEET[/react_click_to_tweet]
</code></pre>
<p>The index.js has:</p>
<pre><code>ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
</code></pre>
<p>But this isn't working.
Any suggestions?</p>
<p>Furthermore, how aI can pass $atts to pass for example attributes to modify the CSS at runtime?</p>
<p>[edit] Based on the suggestions @Paul Burilichev and @belinus I have done the following changes:</p>
<p>I tried what they have about <a href="https://developer.wordpress.org/plugins/javascript/" rel="nofollow noreferrer">WP AJAX</a> for shortcodes with parameters. I tried: </p>
<pre><code>add_shortcode( 'react_click_to_tweet', 'react_click_to_tweet_test' );
function react_click_to_tweet_test($atts = [], $content = null, $tag = '') {
$o = '';
$o .= '<div id="tweet" >';
if (!is_null($content)) {
$o .= apply_filters('content', $content);
// run shortcode parser recursively
$o .= do_shortcode($content);
}
// end box
$o .= '</div>';
return $o; //'<div id="root" ></div>';
}
</code></pre>
<p>but, it doesn't work. What am I missing?</p>
<p>Then, I tried:</p>
<pre><code>function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
$data = array(
'text' => $content, // I also tried passing a string 'some content goes here'
'key2' =? 'value2',
);
wp_localize_script( 'plugin-scripts', 'wp_object', $data );
wp_enqueue_script( 'plugin-scripts' );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
</code></pre>
<p>but object is not recognized on my App component. I guess I am still missing something here. my index.js looks like: </p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
//const data = "This is some cool stuff";
ReactDOM.render(
<App />, document.getElementById('root'));
registerServiceWorker();
</code></pre>
<p>And this is my App.js:</p>
<pre><code>import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
const page = window.location.href;
let data = page+'&text='+ wp_object.text;
let twiiterUrl = "https://"+"twitter.com/intent/tweet?url=";
let URL = twiiterUrl+data;
//console.log(wp_object.text);
return (
<div className="App">
<div className="tm-click-to-tweet">
<div className="tm-ctt-text">
<a href={URL} target="_blank">{wp_object.text} </a>
</div>
<a href={URL} className="tm-ctt-btn" target="_blank">Click To Tweet</a>
<div className="tm-ctt-tip"></div>
<div className="clear"></div>
</div>
</div>
);
}
}
export default App;
</code></pre>
<p>It doesn't recognize wp_object;</p>
| [
{
"answer_id": 271436,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress has a function, <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a> that can do this. You create an array of values that you want to access in your JavaScript file and then inject it as an object.</p>\n\n<p>You would modify your enqueue function like this:</p>\n\n<pre><code>function include_react_files() {\n wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );\n\n // add the JS file to the footer - true as the last parameter\n wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );\n $data = array( \n 'key1' => 'value1',\n 'key2' =? 'value2',\n );\n wp_localize_script( 'plugin-scripts', 'object', $data );\n wp_enqueue_script( 'plugin-scripts' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'include_react_files' );\n</code></pre>\n\n<p>Then to access this data, you would simply do <code>object.key1</code>, <code>object.key2</code>, etc. So <code>console.log( object.key1 );</code> will echo <code>value1</code>.</p>\n"
},
{
"answer_id": 271452,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 0,
"selected": false,
"text": "<p>I warn that the next method is going to brake WP coding notation and style, but for the test purposes and a quick start you can include wanted parameters directly to the template files which is placed on a template directory, you know.</p>\n\n<p>Another approach is using of WP AJAX. The last my project was created by this approach. I'm sure, you know what I am about. More information about <a href=\"https://developer.wordpress.org/plugins/javascript/\" rel=\"nofollow noreferrer\">WP AJAX</a>. But here be careful to investigate about availability Ajax request to you unauthorized visitors (not logged in admin!) which includes by a specific hook start <code>wp_ajax_nopriv_</code>.</p>\n\n<p>Don't hesitate - ask questions.</p>\n"
},
{
"answer_id": 337687,
"author": "Leandro Albin",
"author_id": 167831,
"author_profile": "https://wordpress.stackexchange.com/users/167831",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it's later but...\nYou have to access the window object in order to access global variables.</p>\n\n<p>So the example code would be:</p>\n\n<p><code><a href={URL} target=\"_blank\">{window.wp_object.text} </a></code></p>\n\n<p>For reference:\n<a href=\"https://facebook.github.io/create-react-app/docs/using-global-variables\" rel=\"nofollow noreferrer\">https://facebook.github.io/create-react-app/docs/using-global-variables</a></p>\n"
},
{
"answer_id": 340173,
"author": "Sdaland2",
"author_id": 169791,
"author_profile": "https://wordpress.stackexchange.com/users/169791",
"pm_score": 0,
"selected": false,
"text": "<p>I struggled with this for awhile. The best solution I could come up with was to create a JSON file in within my create-react-app then have wordpress write to it. I hope this helps someone. </p>\n\n<p>I run this on plugin activation</p>\n\n<pre>\nfunction json_config_file() {\n\n $file = plugin_dir_path( __DIR__ ).'PATH_TO_REACT_SRC_FOLDER/wordpress.json';\n\n $json = array(\n key=> value\n );\n\n $fp = fopen($file, 'w');\n fwrite($fp, json_encode($json));\n fclose($fp);\n }\n</pre>\n\n<p>Then in my app.js I can call </p>\n\n<pre>\nlet wordpress = require('./wordpress.json');\n</pre>\n\n<p>and call the values with </p>\n\n<pre>\nconsole.log(wordpress.value)\n</pre>\n"
}
]
| 2017/06/26 | [
"https://wordpress.stackexchange.com/questions/271425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122642/"
]
| I am experimenting creating a WordPress plugin using create-react-app. To make things simple, I am trying to develop a click-to-tweet plugin.
The shortcode part (in PHP ) looks like:
```
// Shortcode to output needed markup
add_shortcode( 'react_click_to_tweet', 'react_click_to_tweet_test' );
function react_click_to_tweet_test($atts = [], $content = null, $tag = '') {
return '<div id="root" data=' . $content . '></div>';
}
function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_enqueue_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
```
$content should be the text to tweet that I want to pass with the shortcode as:
```
[react_click_to_tweet]TEXT TO TWEET[/react_click_to_tweet]
```
The index.js has:
```
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
```
But this isn't working.
Any suggestions?
Furthermore, how aI can pass $atts to pass for example attributes to modify the CSS at runtime?
[edit] Based on the suggestions @Paul Burilichev and @belinus I have done the following changes:
I tried what they have about [WP AJAX](https://developer.wordpress.org/plugins/javascript/) for shortcodes with parameters. I tried:
```
add_shortcode( 'react_click_to_tweet', 'react_click_to_tweet_test' );
function react_click_to_tweet_test($atts = [], $content = null, $tag = '') {
$o = '';
$o .= '<div id="tweet" >';
if (!is_null($content)) {
$o .= apply_filters('content', $content);
// run shortcode parser recursively
$o .= do_shortcode($content);
}
// end box
$o .= '</div>';
return $o; //'<div id="root" ></div>';
}
```
but, it doesn't work. What am I missing?
Then, I tried:
```
function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
$data = array(
'text' => $content, // I also tried passing a string 'some content goes here'
'key2' =? 'value2',
);
wp_localize_script( 'plugin-scripts', 'wp_object', $data );
wp_enqueue_script( 'plugin-scripts' );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
```
but object is not recognized on my App component. I guess I am still missing something here. my index.js looks like:
```
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
//const data = "This is some cool stuff";
ReactDOM.render(
<App />, document.getElementById('root'));
registerServiceWorker();
```
And this is my App.js:
```
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
const page = window.location.href;
let data = page+'&text='+ wp_object.text;
let twiiterUrl = "https://"+"twitter.com/intent/tweet?url=";
let URL = twiiterUrl+data;
//console.log(wp_object.text);
return (
<div className="App">
<div className="tm-click-to-tweet">
<div className="tm-ctt-text">
<a href={URL} target="_blank">{wp_object.text} </a>
</div>
<a href={URL} className="tm-ctt-btn" target="_blank">Click To Tweet</a>
<div className="tm-ctt-tip"></div>
<div className="clear"></div>
</div>
</div>
);
}
}
export default App;
```
It doesn't recognize wp\_object; | WordPress has a function, [`wp_localize_script()`](https://developer.wordpress.org/reference/functions/wp_localize_script/) that can do this. You create an array of values that you want to access in your JavaScript file and then inject it as an object.
You would modify your enqueue function like this:
```
function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
$data = array(
'key1' => 'value1',
'key2' =? 'value2',
);
wp_localize_script( 'plugin-scripts', 'object', $data );
wp_enqueue_script( 'plugin-scripts' );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
```
Then to access this data, you would simply do `object.key1`, `object.key2`, etc. So `console.log( object.key1 );` will echo `value1`. |
271,443 | <p>How do I call a custom post type with <code>WP_Query</code>?</p>
<p>This is my custom post type. How do I display it in my code?</p>
<pre><code><?php
// Hooking up our function to theme setup
add_action( 'init', 'create_post_type' );
add_theme_support('post-thumbnails');
function setup_types() {
register_post_type('mytype', array(
'label' => __('My type'),
'supports' => array( 'title', 'editor', 'thumbnail', 'revisions' ),
'show_ui' => true,
));
}
add_action('init', 'setup_types');
?>
</code></pre>
| [
{
"answer_id": 271436,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress has a function, <a href=\"https://developer.wordpress.org/reference/functions/wp_localize_script/\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a> that can do this. You create an array of values that you want to access in your JavaScript file and then inject it as an object.</p>\n\n<p>You would modify your enqueue function like this:</p>\n\n<pre><code>function include_react_files() {\n wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );\n\n // add the JS file to the footer - true as the last parameter\n wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );\n $data = array( \n 'key1' => 'value1',\n 'key2' =? 'value2',\n );\n wp_localize_script( 'plugin-scripts', 'object', $data );\n wp_enqueue_script( 'plugin-scripts' );\n}\n\nadd_action( 'wp_enqueue_scripts', 'include_react_files' );\n</code></pre>\n\n<p>Then to access this data, you would simply do <code>object.key1</code>, <code>object.key2</code>, etc. So <code>console.log( object.key1 );</code> will echo <code>value1</code>.</p>\n"
},
{
"answer_id": 271452,
"author": "Paul Burilichev",
"author_id": 122299,
"author_profile": "https://wordpress.stackexchange.com/users/122299",
"pm_score": 0,
"selected": false,
"text": "<p>I warn that the next method is going to brake WP coding notation and style, but for the test purposes and a quick start you can include wanted parameters directly to the template files which is placed on a template directory, you know.</p>\n\n<p>Another approach is using of WP AJAX. The last my project was created by this approach. I'm sure, you know what I am about. More information about <a href=\"https://developer.wordpress.org/plugins/javascript/\" rel=\"nofollow noreferrer\">WP AJAX</a>. But here be careful to investigate about availability Ajax request to you unauthorized visitors (not logged in admin!) which includes by a specific hook start <code>wp_ajax_nopriv_</code>.</p>\n\n<p>Don't hesitate - ask questions.</p>\n"
},
{
"answer_id": 337687,
"author": "Leandro Albin",
"author_id": 167831,
"author_profile": "https://wordpress.stackexchange.com/users/167831",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe it's later but...\nYou have to access the window object in order to access global variables.</p>\n\n<p>So the example code would be:</p>\n\n<p><code><a href={URL} target=\"_blank\">{window.wp_object.text} </a></code></p>\n\n<p>For reference:\n<a href=\"https://facebook.github.io/create-react-app/docs/using-global-variables\" rel=\"nofollow noreferrer\">https://facebook.github.io/create-react-app/docs/using-global-variables</a></p>\n"
},
{
"answer_id": 340173,
"author": "Sdaland2",
"author_id": 169791,
"author_profile": "https://wordpress.stackexchange.com/users/169791",
"pm_score": 0,
"selected": false,
"text": "<p>I struggled with this for awhile. The best solution I could come up with was to create a JSON file in within my create-react-app then have wordpress write to it. I hope this helps someone. </p>\n\n<p>I run this on plugin activation</p>\n\n<pre>\nfunction json_config_file() {\n\n $file = plugin_dir_path( __DIR__ ).'PATH_TO_REACT_SRC_FOLDER/wordpress.json';\n\n $json = array(\n key=> value\n );\n\n $fp = fopen($file, 'w');\n fwrite($fp, json_encode($json));\n fclose($fp);\n }\n</pre>\n\n<p>Then in my app.js I can call </p>\n\n<pre>\nlet wordpress = require('./wordpress.json');\n</pre>\n\n<p>and call the values with </p>\n\n<pre>\nconsole.log(wordpress.value)\n</pre>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271443",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122658/"
]
| How do I call a custom post type with `WP_Query`?
This is my custom post type. How do I display it in my code?
```
<?php
// Hooking up our function to theme setup
add_action( 'init', 'create_post_type' );
add_theme_support('post-thumbnails');
function setup_types() {
register_post_type('mytype', array(
'label' => __('My type'),
'supports' => array( 'title', 'editor', 'thumbnail', 'revisions' ),
'show_ui' => true,
));
}
add_action('init', 'setup_types');
?>
``` | WordPress has a function, [`wp_localize_script()`](https://developer.wordpress.org/reference/functions/wp_localize_script/) that can do this. You create an array of values that you want to access in your JavaScript file and then inject it as an object.
You would modify your enqueue function like this:
```
function include_react_files() {
wp_enqueue_style( 'prefix-style', plugins_url('css/main.ae114d0c.css', __FILE__) );
// add the JS file to the footer - true as the last parameter
wp_register_script( 'plugin-scripts', plugins_url('js/main.d8745ba2.js', __FILE__),array(), '0.0.1', true );
$data = array(
'key1' => 'value1',
'key2' =? 'value2',
);
wp_localize_script( 'plugin-scripts', 'object', $data );
wp_enqueue_script( 'plugin-scripts' );
}
add_action( 'wp_enqueue_scripts', 'include_react_files' );
```
Then to access this data, you would simply do `object.key1`, `object.key2`, etc. So `console.log( object.key1 );` will echo `value1`. |
271,448 | <p>I want to show recent posts in my Android application and I'm using this end point to get the list of posts <a href="https://www.geekdashboard.com/wp-json/wp/v2/posts" rel="nofollow noreferrer">https://www.geekdashboard.com/wp-json/wp/v2/posts</a></p>
<p>How can I get the complete URL of the featured image instead of its id?</p>
<pre><code>"featured_media": 39913,
</code></pre>
<p>I don't want to use any plugins and is it possible to it using functions.php?</p>
| [
{
"answer_id": 271455,
"author": "ville6000",
"author_id": 62041,
"author_profile": "https://wordpress.stackexchange.com/users/62041",
"pm_score": 4,
"selected": true,
"text": "<p>You can modifiy REST API responses in themes functions.php like this.</p>\n\n<pre><code>function ws_register_images_field() {\n register_rest_field( \n 'post',\n 'images',\n array(\n 'get_callback' => 'ws_get_images_urls',\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n}\n\nadd_action( 'rest_api_init', 'ws_register_images_field' );\n\nfunction ws_get_images_urls( $object, $field_name, $request ) {\n $medium = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'medium' );\n $medium_url = $medium['0'];\n\n $large = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'large' );\n $large_url = $large['0'];\n\n return array(\n 'medium' => $medium_url,\n 'large' => $large_url,\n );\n}\n</code></pre>\n\n<p>If you can't modify the REST API response, you can request the media info like this <code>curl http://your-site.com/wp-json/wp/v2/media/<id></code></p>\n"
},
{
"answer_id": 318390,
"author": "The Billionaire Guy",
"author_id": 153185,
"author_profile": "https://wordpress.stackexchange.com/users/153185",
"pm_score": 0,
"selected": false,
"text": "<p>modifying @ville6000 example, i was able to solve my own problem,</p>\n\n<pre><code> add_action( 'rest_api_init', 'ws_register_images_field' );\nfunction ws_register_images_field() {\n register_rest_field( \n 'post', //custom post name\n 'attachment_url_images', //array name of your choice\n array(\n 'get_callback' => 'ws_get_images_urls',\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n}\n\n\nfunction ws_get_images_urls( $object, $field_name, $request ) {\n\n $custom_fields = get_post_custom($object['id']);\n $main_image = $custom_fields['your_custom_images_array_name'];\n $image_urls = array();\n\n foreach ( $main_image as $key => $value ) {\n $imagesID = explode(',' ,$value);\n foreach ($imagesID as $id => $value) {\n $image_urls[ $key ] = wp_get_attachment_url($value);\n //$custom_fields[ $id ] = $image_urls;\n }\n };\n\n return $image_urls;\n //return count($main_image);\n}\n</code></pre>\n\n<p>Add to themes functions.php\nHappy Coding...</p>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116313/"
]
| I want to show recent posts in my Android application and I'm using this end point to get the list of posts <https://www.geekdashboard.com/wp-json/wp/v2/posts>
How can I get the complete URL of the featured image instead of its id?
```
"featured_media": 39913,
```
I don't want to use any plugins and is it possible to it using functions.php? | You can modifiy REST API responses in themes functions.php like this.
```
function ws_register_images_field() {
register_rest_field(
'post',
'images',
array(
'get_callback' => 'ws_get_images_urls',
'update_callback' => null,
'schema' => null,
)
);
}
add_action( 'rest_api_init', 'ws_register_images_field' );
function ws_get_images_urls( $object, $field_name, $request ) {
$medium = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'medium' );
$medium_url = $medium['0'];
$large = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), 'large' );
$large_url = $large['0'];
return array(
'medium' => $medium_url,
'large' => $large_url,
);
}
```
If you can't modify the REST API response, you can request the media info like this `curl http://your-site.com/wp-json/wp/v2/media/<id>` |
271,451 | <p>Simple questions - how do I delete all categories programatically?</p>
<p>For instance this returns a list of all categories </p>
<pre><code>$args = array(
"hide_empty" => 0,
"type" => "post",
"orderby" => "name",
"order" => "ASC"
);
$types = get_categories($args);
</code></pre>
<p>How do I simply delete them so I can replace them with other categories?</p>
| [
{
"answer_id": 271458,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>Please have look on the below code block-</p>\n\n<pre><code>$args = array(\n \"hide_empty\" => 0,\n \"type\" => \"post\",\n \"orderby\" => \"name\",\n \"order\" => \"ASC\"\n);\n$types = get_categories($args);\n\nforeach ( $types as $type) {\n wp_delete_category( $type->ID );\n}\n</code></pre>\n\n<p>The function <a href=\"https://codex.wordpress.org/Function_Reference/wp_delete_category\" rel=\"nofollow noreferrer\"><code>wp_delete_category</code></a> will delete a single category. So we need to run a loop through <code>$types</code> to delete each single category.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 359905,
"author": "wp-mario.ru",
"author_id": 117524,
"author_profile": "https://wordpress.stackexchange.com/users/117524",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$cats = get_categories( [\n 'hide_empty' => 0\n] );\nforeach( $cats as $cat ) {\n wp_delete_category( $cat->term_id );\n}\n</code></pre>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271451",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122667/"
]
| Simple questions - how do I delete all categories programatically?
For instance this returns a list of all categories
```
$args = array(
"hide_empty" => 0,
"type" => "post",
"orderby" => "name",
"order" => "ASC"
);
$types = get_categories($args);
```
How do I simply delete them so I can replace them with other categories? | Please have look on the below code block-
```
$args = array(
"hide_empty" => 0,
"type" => "post",
"orderby" => "name",
"order" => "ASC"
);
$types = get_categories($args);
foreach ( $types as $type) {
wp_delete_category( $type->ID );
}
```
The function [`wp_delete_category`](https://codex.wordpress.org/Function_Reference/wp_delete_category) will delete a single category. So we need to run a loop through `$types` to delete each single category.
Hope that helps. |
271,478 | <p>How can I set the default subtitle in wordpress videos?</p>
<p>Here is the shortcode that wp created after adding a video with a subtitle from media:</p>
<pre><code>[video
width="960"
height="540"
mp4="example.com/wp-content/uploads/test.mp4"
]<track
srclang="En"
label="English"
kind="subtitles"
src="example.com/wp-content/uploads/test.vtt"
/>[/video]
</code></pre>
<p>Now when I see the post in FO, I have to click on "cc" in video control bar and choose "English". The default is "None".</p>
<p>Now how can I change this default to English so that the user doesn't have to choose subtitle?</p>
| [
{
"answer_id": 271458,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 3,
"selected": true,
"text": "<p>Please have look on the below code block-</p>\n\n<pre><code>$args = array(\n \"hide_empty\" => 0,\n \"type\" => \"post\",\n \"orderby\" => \"name\",\n \"order\" => \"ASC\"\n);\n$types = get_categories($args);\n\nforeach ( $types as $type) {\n wp_delete_category( $type->ID );\n}\n</code></pre>\n\n<p>The function <a href=\"https://codex.wordpress.org/Function_Reference/wp_delete_category\" rel=\"nofollow noreferrer\"><code>wp_delete_category</code></a> will delete a single category. So we need to run a loop through <code>$types</code> to delete each single category.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 359905,
"author": "wp-mario.ru",
"author_id": 117524,
"author_profile": "https://wordpress.stackexchange.com/users/117524",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$cats = get_categories( [\n 'hide_empty' => 0\n] );\nforeach( $cats as $cat ) {\n wp_delete_category( $cat->term_id );\n}\n</code></pre>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122684/"
]
| How can I set the default subtitle in wordpress videos?
Here is the shortcode that wp created after adding a video with a subtitle from media:
```
[video
width="960"
height="540"
mp4="example.com/wp-content/uploads/test.mp4"
]<track
srclang="En"
label="English"
kind="subtitles"
src="example.com/wp-content/uploads/test.vtt"
/>[/video]
```
Now when I see the post in FO, I have to click on "cc" in video control bar and choose "English". The default is "None".
Now how can I change this default to English so that the user doesn't have to choose subtitle? | Please have look on the below code block-
```
$args = array(
"hide_empty" => 0,
"type" => "post",
"orderby" => "name",
"order" => "ASC"
);
$types = get_categories($args);
foreach ( $types as $type) {
wp_delete_category( $type->ID );
}
```
The function [`wp_delete_category`](https://codex.wordpress.org/Function_Reference/wp_delete_category) will delete a single category. So we need to run a loop through `$types` to delete each single category.
Hope that helps. |
271,506 | <p>Currently, my homepage contains a few of the latest posts. Therefore, when the homepage is shared via social media (i.e. Facebook), the thumbnail image which is displayed comes from the top image in the latest post.</p>
<p>What I am trying to do, is to set it so that when the homepage is shared, a specific, default image will be displayed. However, the image must only be displayed when the homepage is shared, and should not otherwise appear on the site. What would be the best way to do this?</p>
| [
{
"answer_id": 271508,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 4,
"selected": true,
"text": "<p>Several options:</p>\n\n<p><strong>Out-of-the-box plugin</strong></p>\n\n<p>If you're using Yoast WordPress SEO, you have a built-in setting for Facebook images. Under your SEO > Social menu, go to the Facebook tab and select an image under \"Frontpage settings.\" You can also set an image as a fallback, for posts that have no featured image, under \"Default settings.\"</p>\n\n<p>Other SEO plugins may have similar capabilities.</p>\n\n<p><strong>Child theme</strong></p>\n\n<p>You can create a child theme or modify a custom theme. First, make sure the theme supports a site logo. If not, <a href=\"https://codex.wordpress.org/Theme_Logo\" rel=\"noreferrer\">add custom logo support</a>.</p>\n\n<p>Next, edit or copy <code>header.php</code> into your new child theme. Inside the <code><head></head></code> tags, include a check for <code>if(is_front_page())</code> or <code>if(is_home())</code> depending on your needs. Sounds like either would work in your case.</p>\n\n<p>If the condition is met, grab the custom logo URL</p>\n\n<pre><code>$image = wp_get_attachment_image_url(get_theme_mod('custom_logo'), 'large');\n</code></pre>\n\n<p>and output it within Open Graph tags:</p>\n\n<pre><code><meta property=\"og:image\" content=\"<?php echo $image; ?>\" />\n<meta name=\"twitter:image\" content=\"<?php echo $image; ?>\" />\n</code></pre>\n\n<p><strong>Custom plugin</strong></p>\n\n<p>You could also create your own plugin, if you don't want to use Yoast WordPress SEO or fiddle with the theme. The risk is that an existing theme or plugin may already output a featured image, so you'd want to check your page source and make sure nothing else is setting a featured image. I assume this is the case since your current theme and plugins are setting the most-recently-published post's image when you try to share it.</p>\n\n<p>Basically, you would add an action for the <code>wp_head</code> hook. Your action would output the Open Graph and Twitter image data just like you would if you chose the first option, working with the theme.</p>\n\n<p>You'd have to decide whether to hard-code the image into your plugin, or whether you would create an options page somewhere in wp-admin where you could change the image whenever you wanted.</p>\n"
},
{
"answer_id": 271509,
"author": "Jonny Perl",
"author_id": 40765,
"author_profile": "https://wordpress.stackexchange.com/users/40765",
"pm_score": 1,
"selected": false,
"text": "<p>Different social platforms use different methods.</p>\n\n<p>For Facebook, you need a set of <code><meta></code> tags with <code>og</code> properties - e.g. <code>og:url</code>, <code>og:type</code>, <code>og:description</code> and <code>og:image</code>. <code>og:image</code> should contain the full path to the image you want to be displayed.</p>\n\n<p>Twitter is similar but has their own 'card' mechanism which requires its own set of <code>meta</code> tags - e.g. <code>name=\"twitter:card\"</code> and <code>name=\"twitter:image\"</code></p>\n\n<p>I believe there are plugins to handle this. I have my own simple function which uses the thumbnail of the page, or a fallback if this isn't set.</p>\n"
},
{
"answer_id": 271510,
"author": "Dihgg",
"author_id": 107503,
"author_profile": "https://wordpress.stackexchange.com/users/107503",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://developers.facebook.com/docs/sharing/webmasters\" rel=\"nofollow noreferrer\">OG meta tags</a> is probably what you are looking for, in this case :</p>\n\n<pre><code><meta property=\"og:image\"content=\"path/to/foo.jpg\" />\n</code></pre>\n\n<p>put inside a if <code>is_home()</code> and hopefully it will work</p>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106748/"
]
| Currently, my homepage contains a few of the latest posts. Therefore, when the homepage is shared via social media (i.e. Facebook), the thumbnail image which is displayed comes from the top image in the latest post.
What I am trying to do, is to set it so that when the homepage is shared, a specific, default image will be displayed. However, the image must only be displayed when the homepage is shared, and should not otherwise appear on the site. What would be the best way to do this? | Several options:
**Out-of-the-box plugin**
If you're using Yoast WordPress SEO, you have a built-in setting for Facebook images. Under your SEO > Social menu, go to the Facebook tab and select an image under "Frontpage settings." You can also set an image as a fallback, for posts that have no featured image, under "Default settings."
Other SEO plugins may have similar capabilities.
**Child theme**
You can create a child theme or modify a custom theme. First, make sure the theme supports a site logo. If not, [add custom logo support](https://codex.wordpress.org/Theme_Logo).
Next, edit or copy `header.php` into your new child theme. Inside the `<head></head>` tags, include a check for `if(is_front_page())` or `if(is_home())` depending on your needs. Sounds like either would work in your case.
If the condition is met, grab the custom logo URL
```
$image = wp_get_attachment_image_url(get_theme_mod('custom_logo'), 'large');
```
and output it within Open Graph tags:
```
<meta property="og:image" content="<?php echo $image; ?>" />
<meta name="twitter:image" content="<?php echo $image; ?>" />
```
**Custom plugin**
You could also create your own plugin, if you don't want to use Yoast WordPress SEO or fiddle with the theme. The risk is that an existing theme or plugin may already output a featured image, so you'd want to check your page source and make sure nothing else is setting a featured image. I assume this is the case since your current theme and plugins are setting the most-recently-published post's image when you try to share it.
Basically, you would add an action for the `wp_head` hook. Your action would output the Open Graph and Twitter image data just like you would if you chose the first option, working with the theme.
You'd have to decide whether to hard-code the image into your plugin, or whether you would create an options page somewhere in wp-admin where you could change the image whenever you wanted. |
271,511 | <p>I'm registering custom post type in the plugin, but want to allow users of the plugin modify it afterwards (e.g. if they are installing for clients, etc.)</p>
<pre><code>function create_reviews_post_type() {
register_post_type('reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type');
</code></pre>
<p>What is best way to achieve this?
E.g. I want to change <strong>name</strong>, <strong>singular name</strong> and <strong>slug</strong> in future. </p>
<p>I understand that there is a <a href="https://wordpress.stackexchange.com/questions/41988/redeclare-change-slug-of-a-plugins-custom-post-type">similar question</a>, but</p>
<ol>
<li>it 5 years old and I hope there can be an easier way,</li>
<li>it doesn't cover the name part</li>
</ol>
| [
{
"answer_id": 271513,
"author": "Spartacus",
"author_id": 32329,
"author_profile": "https://wordpress.stackexchange.com/users/32329",
"pm_score": 2,
"selected": false,
"text": "<p>You could do something simple like providing them filters to modify.</p>\n\n<pre><code>function create_reviews_post_type() {\n $slug = apply_filters('plugin_cpt_slug','reviews');\n $name = apply_filters('plugin_cpt_name','Reviews');\n $sname = apply_filters('plugin_cpt_name_singular','Review');\n\n register_post_type($slug, array(\n 'labels' => array(\n 'name' => __($name),\n 'singular_name' => __($sname)\n ),\n 'public' => true,\n 'has_archive' => true,\n )\n );\n}\nadd_action('init', 'create_reviews_post_type');\n</code></pre>\n\n<p>They can modify them using add_filter() like so:</p>\n\n<pre><code>add_filter('plugin_cpt_slug','change_plugin_cpt_slug');\nfunction change_plugin_cpt_slug(){\n return 'complaints';\n}\n//etc., etc.\n</code></pre>\n\n<p>This is admittedly a verbose way of doing this, but it works.</p>\n"
},
{
"answer_id": 271539,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress provides the <a href=\"https://developer.wordpress.org/reference/hooks/register_post_type_args/\" rel=\"nofollow noreferrer\"><code>register_post_type_args</code> filter</a> to let users do this:</p>\n\n<pre><code>function wpd_modify_post_type( $args, $post_type ){\n if( 'reviews' == $post_type ){\n $args['labels']['name'] = 'New name';\n $args['labels']['singular_name'] = 'New singular name';\n $args['rewrite']['slug'] = 'new-slug';\n }\n return $args;\n}\nadd_filter( 'register_post_type_args', 'wpd_modify_post_type', 10, 2 );\n</code></pre>\n\n<p>Keep in mind that if the slug changes, the user will need to flush rewrite rules manually for the new slug to start working, which can be done by visiting the Settings > Permalinks page in admin.</p>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271511",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
]
| I'm registering custom post type in the plugin, but want to allow users of the plugin modify it afterwards (e.g. if they are installing for clients, etc.)
```
function create_reviews_post_type() {
register_post_type('reviews', array(
'labels' => array(
'name' => __('Reviews'),
'singular_name' => __('Review')
),
'public' => true,
'has_archive' => true,
)
);
}
add_action('init', 'create_reviews_post_type');
```
What is best way to achieve this?
E.g. I want to change **name**, **singular name** and **slug** in future.
I understand that there is a [similar question](https://wordpress.stackexchange.com/questions/41988/redeclare-change-slug-of-a-plugins-custom-post-type), but
1. it 5 years old and I hope there can be an easier way,
2. it doesn't cover the name part | WordPress provides the [`register_post_type_args` filter](https://developer.wordpress.org/reference/hooks/register_post_type_args/) to let users do this:
```
function wpd_modify_post_type( $args, $post_type ){
if( 'reviews' == $post_type ){
$args['labels']['name'] = 'New name';
$args['labels']['singular_name'] = 'New singular name';
$args['rewrite']['slug'] = 'new-slug';
}
return $args;
}
add_filter( 'register_post_type_args', 'wpd_modify_post_type', 10, 2 );
```
Keep in mind that if the slug changes, the user will need to flush rewrite rules manually for the new slug to start working, which can be done by visiting the Settings > Permalinks page in admin. |
271,515 | <p>From what I've read (<a href="https://wordpress.stackexchange.com/questions/246679/check-if-favicon-is-set-in-customizer">Check if Favicon is set in Customizer</a> and others), it appears checking to see if a site icon is set in a theme should be easy. It doesn't seem to be working for me. I'd like to have a set of default site icons set in my theme that can be overwritten if a user uploads a site icon. The code I have now is:</p>
<pre><code> <?php
if( false === get_option( 'site_icon', false ) ) {
?>
<link rel="apple-touch-icon" sizes="57x57" href="<?php echo get_stylesheet_directory_uri(); ?>/icons/apple-icon-57x57.png">
<!-- MORE ICONS OUTPUT HERE -->
<?php
}
?>
</code></pre>
<p>This doesn't seem to be working though. Regardless if a site icon is set or not, it will not output. Furthermore, even after deleting an icon from the Customizer section, it stays on the site (even after clearing the site and local cache). </p>
<p>Everything I've read says the site icon should work without any theme support, but it doesn't seem to be working for me. Any insights or something I might be missing?</p>
| [
{
"answer_id": 271519,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>Let's check if the site icon is set, and then print it:</p>\n\n<pre><code><?php if (get_option('site_icon')) { ?>\n <link rel=\"apple-touch-icon\" href=\"<?php echo wp_get_attachment_image_url(get_option('site_icon'),'full') ?>\"><?php\n} else { ?>\n <link rel=\"apple-touch-icon\" sizes=\"57x57\" href=\"<?php echo get_stylesheet_directory_uri(); ?>/icons/apple-icon-57x57.png\"><?php\n} ?>\n</code></pre>\n\n<p>I'm using this at the moment I'm writing this answer, and it works. This way you can debug to see if there is a site icon in your options or not since this code will output something anyway.</p>\n\n<h2>UPDATE</h2>\n\n<p>As mentioned in the comment by @birgire, my answer suits the best if you are going to use this code some place other than header, or your theme doesn't have a <code>wp_head</code> function. </p>\n\n<p>If it does, then:</p>\n\n<blockquote>\n <p>It's added automatically by default via the <code>wp_site_icon()</code> function\n through the <code>wp_head/login_head</code> actions.</p>\n</blockquote>\n"
},
{
"answer_id": 271581,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>There exists a special function to check if the <em>site icon</em> is set, namely the <a href=\"https://developer.wordpress.org/reference/functions/has_site_icon/\" rel=\"nofollow noreferrer\"><code>has_site_icon()</code></a> function. </p>\n\n<p>So you could try:</p>\n\n<pre><code>add_action( 'wp_head', 'wpse_default_site_icon', 99 );\nadd_action( 'login_head', 'wpse_default_site_icon', 99 );\n\nfunction wpse_default_site_icon()\n{\n if( ! has_site_icon() && ! is_customize_preview() )\n {\n // your default icons here\n }\n} \n</code></pre>\n\n<p>The case when the site icon is set, is already handled by:</p>\n\n<pre><code>add_action( 'wp_head', 'wp_site_icon', 99 );\nadd_action( 'login_head', 'wp_site_icon', 99 );\n</code></pre>\n"
}
]
| 2017/06/27 | [
"https://wordpress.stackexchange.com/questions/271515",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31284/"
]
| From what I've read ([Check if Favicon is set in Customizer](https://wordpress.stackexchange.com/questions/246679/check-if-favicon-is-set-in-customizer) and others), it appears checking to see if a site icon is set in a theme should be easy. It doesn't seem to be working for me. I'd like to have a set of default site icons set in my theme that can be overwritten if a user uploads a site icon. The code I have now is:
```
<?php
if( false === get_option( 'site_icon', false ) ) {
?>
<link rel="apple-touch-icon" sizes="57x57" href="<?php echo get_stylesheet_directory_uri(); ?>/icons/apple-icon-57x57.png">
<!-- MORE ICONS OUTPUT HERE -->
<?php
}
?>
```
This doesn't seem to be working though. Regardless if a site icon is set or not, it will not output. Furthermore, even after deleting an icon from the Customizer section, it stays on the site (even after clearing the site and local cache).
Everything I've read says the site icon should work without any theme support, but it doesn't seem to be working for me. Any insights or something I might be missing? | There exists a special function to check if the *site icon* is set, namely the [`has_site_icon()`](https://developer.wordpress.org/reference/functions/has_site_icon/) function.
So you could try:
```
add_action( 'wp_head', 'wpse_default_site_icon', 99 );
add_action( 'login_head', 'wpse_default_site_icon', 99 );
function wpse_default_site_icon()
{
if( ! has_site_icon() && ! is_customize_preview() )
{
// your default icons here
}
}
```
The case when the site icon is set, is already handled by:
```
add_action( 'wp_head', 'wp_site_icon', 99 );
add_action( 'login_head', 'wp_site_icon', 99 );
``` |
271,549 | <p>I want to call a function on particular page like 'contact-us' from function.php of child theme.</p>
<p>i tried this function</p>
<pre><code> if( is_page('contact-us')) {
echo "hello check";
//either in about us, or contact, or management page is in view
} else {
echo "Not working";
}
</code></pre>
<p>But getting else part on every page.</p>
<pre><code> if(is_page(37)){
echo "page 37";
} else { echo "Not working" }
</code></pre>
<p>Getting else part</p>
<pre><code>$current_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$contactUsId = url_to_postid( $current_url );
if($contactUsId == '37'){
echo "hello";
}
</code></pre>
<p>But this works , can any one one help me to know why first two function print else part.</p>
| [
{
"answer_id": 271556,
"author": "DrewAPicture",
"author_id": 33309,
"author_profile": "https://wordpress.stackexchange.com/users/33309",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that you're trying to use <code>is_page()</code>, a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, <code>wp_head</code>.</p>\n\n<pre><code>function prefix_run_on_contact_us() {\n if( is_page('contact-us')) {\n echo \"hello check\"; \n //either in about us, or contact, or management page is in view\n } else {\n echo \"Not working\";\n }\n}\nadd_action( 'wp_head', 'prefix_run_on_contact_us' );\n</code></pre>\n"
},
{
"answer_id": 271557,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<p>What hook do You use when You try use this functions? Did You think about it? It happen me all the time :) Here You have earliest possible hook in my opinion i tested few and they were too soon. </p>\n\n<p>Solution 1:</p>\n\n<pre><code>add_action('parse_query', function () {\n\nif( is_page('contact-us')) {\n\n echo \"hello check\";\n //either in about us, or contact, or management page is in view\n} else {\n echo \"Not working\";\n}});\n</code></pre>\n\n<p>Solution 2: </p>\n\n<pre><code>add_action('parse_query', function () {\n\n if( 'contact-us' == get_query_var('pagename') ) {\n echo \"hello check\";\n //either in about us, or contact, or management page is in view\n } else {\n echo \"Not working\";\n }\n});\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116990/"
]
| I want to call a function on particular page like 'contact-us' from function.php of child theme.
i tried this function
```
if( is_page('contact-us')) {
echo "hello check";
//either in about us, or contact, or management page is in view
} else {
echo "Not working";
}
```
But getting else part on every page.
```
if(is_page(37)){
echo "page 37";
} else { echo "Not working" }
```
Getting else part
```
$current_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$contactUsId = url_to_postid( $current_url );
if($contactUsId == '37'){
echo "hello";
}
```
But this works , can any one one help me to know why first two function print else part. | The problem is that you're trying to use `is_page()`, a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, `wp_head`.
```
function prefix_run_on_contact_us() {
if( is_page('contact-us')) {
echo "hello check";
//either in about us, or contact, or management page is in view
} else {
echo "Not working";
}
}
add_action( 'wp_head', 'prefix_run_on_contact_us' );
``` |
271,550 | <p>I'm looking for widget or php query which I will be able to use as something like "on this day in history".</p>
<p>This query I want to show:
Posts published in the past on the same day and month, from whole years of publication.</p>
<p>Thank you in advance for help. </p>
| [
{
"answer_id": 271556,
"author": "DrewAPicture",
"author_id": 33309,
"author_profile": "https://wordpress.stackexchange.com/users/33309",
"pm_score": 3,
"selected": true,
"text": "<p>The problem is that you're trying to use <code>is_page()</code>, a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, <code>wp_head</code>.</p>\n\n<pre><code>function prefix_run_on_contact_us() {\n if( is_page('contact-us')) {\n echo \"hello check\"; \n //either in about us, or contact, or management page is in view\n } else {\n echo \"Not working\";\n }\n}\nadd_action( 'wp_head', 'prefix_run_on_contact_us' );\n</code></pre>\n"
},
{
"answer_id": 271557,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<p>What hook do You use when You try use this functions? Did You think about it? It happen me all the time :) Here You have earliest possible hook in my opinion i tested few and they were too soon. </p>\n\n<p>Solution 1:</p>\n\n<pre><code>add_action('parse_query', function () {\n\nif( is_page('contact-us')) {\n\n echo \"hello check\";\n //either in about us, or contact, or management page is in view\n} else {\n echo \"Not working\";\n}});\n</code></pre>\n\n<p>Solution 2: </p>\n\n<pre><code>add_action('parse_query', function () {\n\n if( 'contact-us' == get_query_var('pagename') ) {\n echo \"hello check\";\n //either in about us, or contact, or management page is in view\n } else {\n echo \"Not working\";\n }\n});\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271550",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122729/"
]
| I'm looking for widget or php query which I will be able to use as something like "on this day in history".
This query I want to show:
Posts published in the past on the same day and month, from whole years of publication.
Thank you in advance for help. | The problem is that you're trying to use `is_page()`, a conditional function intended only to run adjacent to the query, too early. Try running your code inside a callback that 1) only fires on the front-end, 2) fires after the page has partially loaded. For instance, `wp_head`.
```
function prefix_run_on_contact_us() {
if( is_page('contact-us')) {
echo "hello check";
//either in about us, or contact, or management page is in view
} else {
echo "Not working";
}
}
add_action( 'wp_head', 'prefix_run_on_contact_us' );
``` |
271,563 | <p>I am trying to use WordPress with a bootstrap template, class <code>navbar-fixed-top</code> is conflicting with <code>body_class();</code></p>
<p>Is there a workaround to this problem?</p>
<h2>Edit 1:</h2>
<p>Additional details,</p>
<p>I can't see the nav, thet's the main issue. I'm trying to use <code><?php body_class(); ?></code> to fix this up but no results.</p>
<p><a href="https://i.stack.imgur.com/LZQ0f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LZQ0f.png" alt="can't see navbar"></a></p>
<p>Here's the code upto nav:</p>
<pre><code><body id="page-top" <?php body_class(); ?>>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top affix">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top">Start Bootstrap</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#services">Services</a>
</li>
<li>
<a href="#portfolio">Portfolio</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- a lot more code and -->
</body>
</code></pre>
<p>Here's the body tag from page after rendering:</p>
<pre><code><body id="page-top" class="home blog logged-in admin-bar no-customize-support">
</code></pre>
| [
{
"answer_id": 271885,
"author": "Amoy N",
"author_id": 100875,
"author_profile": "https://wordpress.stackexchange.com/users/100875",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use a navwalker to create your bootstrap menu?\nTry <a href=\"https://github.com/wp-bootstrap/wp-bootstrap-navwalker\" rel=\"nofollow noreferrer\">https://github.com/wp-bootstrap/wp-bootstrap-navwalker</a></p>\n\n<p>You can get the fixed-top to add to the menu</p>\n\n<pre><code><nav class=\"navbar navbar-default navbar-fixed-top\" temscope=\"itemscope\" itemtype=\"http://schema.org/SiteNavigationElement\" role=\"navigation\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#navbar\">\n <span class=\"sr-only\">Toggle navigation</span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n <span class=\"icon-bar\"></span>\n </button>\n </div>\n\n <div class=\"collapse navbar-collapse\" id=\"navbar\">\n <ul class=\"nav navbar-nav\"> \n <?php\n wp_nav_menu( array(\n 'menu' => 'primary',\n 'theme_location' => 'primary',\n 'depth' => 2,\n 'container' => 'div',\n 'container_class' => '',\n 'container_id' => 'collapse navbar-collapse',\n 'menu_class' => 'nav navbar-nav',\n 'fallback_cb' => 'wp_bootstrap_navwalker::fallback',\n 'walker' => new wp_bootstrap_navwalker())\n );\n ?>\n </ul>\n </div>\n </div>\n</code></pre>\n"
},
{
"answer_id": 271925,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>The reason that the admin-bar and the navbar are overlapping is because they are both fixed to the top of the screen. There are two ways you can deal with this:</p>\n\n<p>With PHP you can remove the admin bar. Add the following to your functions.php or in a standalone plugin:</p>\n\n<pre><code>add_filter( 'show_admin_bar', '__return_false' );\n</code></pre>\n\n<p>Or with CSS. Add this to your themes style.css or in the customizer:</p>\n\n<pre><code>.admin-bar .navbar { top: 32px; }\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97698/"
]
| I am trying to use WordPress with a bootstrap template, class `navbar-fixed-top` is conflicting with `body_class();`
Is there a workaround to this problem?
Edit 1:
-------
Additional details,
I can't see the nav, thet's the main issue. I'm trying to use `<?php body_class(); ?>` to fix this up but no results.
[](https://i.stack.imgur.com/LZQ0f.png)
Here's the code upto nav:
```
<body id="page-top" <?php body_class(); ?>>
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top affix">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top">Start Bootstrap</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#services">Services</a>
</li>
<li>
<a href="#portfolio">Portfolio</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
<!-- a lot more code and -->
</body>
```
Here's the body tag from page after rendering:
```
<body id="page-top" class="home blog logged-in admin-bar no-customize-support">
``` | Why not use a navwalker to create your bootstrap menu?
Try <https://github.com/wp-bootstrap/wp-bootstrap-navwalker>
You can get the fixed-top to add to the menu
```
<nav class="navbar navbar-default navbar-fixed-top" temscope="itemscope" itemtype="http://schema.org/SiteNavigationElement" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar">
<ul class="nav navbar-nav">
<?php
wp_nav_menu( array(
'menu' => 'primary',
'theme_location' => 'primary',
'depth' => 2,
'container' => 'div',
'container_class' => '',
'container_id' => 'collapse navbar-collapse',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
'walker' => new wp_bootstrap_navwalker())
);
?>
</ul>
</div>
</div>
``` |
271,612 | <p>I am trying to find a function which will add <strong>ADDITIONAL</strong> button next to the standard "Add to cart" button in woo commerce product page.</p>
<ol>
<li>I added a woocommerce folder into my childe theme in order to modify
single-product => add-to-cart => simple.php</li>
<li>Inside simple.php I found the standard "Add to cart" button and after it is
where I want to add my custom additional "checkout" button</li>
</ol>
<p>I found this function:</p>
<pre><code>function woo_redirect_to_checkout() {
$checkout_url = WC()->cart->get_checkout_url();
return $checkout_url;
}
</code></pre>
<p>Which works fine BUT it modify ALL "add to cart" buttons in the site
and I am trying to add it ONLY to the new custom button that I am trying to add
(The new checkout button)
I managed to add a button which redirects to checkout page but doesn't Add the item to the cart prior to going to the checkout</p>
<p>Anyone knows how do I add a NEW button + this button needs to not only go to the checkout page but also trigger the "Add to cart" action at the same time</p>
<p>Thanks</p>
| [
{
"answer_id": 271634,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 5,
"selected": true,
"text": "<p>You dont need to modify your template files for this, instead you can use the WooCommerce hook <code>woocommerce_after_add_to_cart_button</code>. This hook will add content after the \"Add to cart\" button.</p>\n\n<p>If the customer clicks on this button, the product should get added to the cart, and the customer should be send to the checkout page, right?!</p>\n\n<p>Basically you can add products to the cart with a link like this: </p>\n\n<pre><code>http://example.com/cart/?add-to-cart=<product ID>\n</code></pre>\n\n<p>So, using the hook mentioned above, and keeping this URL in mind, we can add a second button with this snippet:</p>\n\n<pre><code>function add_content_after_addtocart() {\n\n // get the current post/product ID\n $current_product_id = get_the_ID();\n\n // get the product based on the ID\n $product = wc_get_product( $current_product_id );\n\n // get the \"Checkout Page\" URL\n $checkout_url = WC()->cart->get_checkout_url();\n\n // run only on simple products\n if( $product->is_type( 'simple' ) ){\n echo '<a href=\"'.$checkout_url.'?add-to-cart='.$current_product_id.'\" class=\"single_add_to_cart_button button alt\">Checkout</a>';\n }\n}\nadd_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );\n</code></pre>\n\n<p>This will add a button after the normal Add to cart button on single product pages.\nAs you can see I also added a check to see if the current product is a simple product or not. If you want to use this with variation, it is more difficult.\nWith these products you need to generate an URL like:</p>\n\n<pre><code>http://example.com/cart/?add-to-cart=123&variation_id=456&attribute_pa_colour=black\n</code></pre>\n\n<hr>\n\n<p>Maybe you also need to check the default WooCommerce option <code>Enable AJAX Add to cart</code> (WooCommerce > Products > Display). I have not tested it with this setting.</p>\n\n<hr>\n\n<p><strong>Update</strong> to include the quantity</p>\n\n<p>If you want to add a quantity you can also append a parameter to our button URL, like so:</p>\n\n<pre><code>http://example.com/cart/?add-to-cart=<product ID>&quantity=<number of quantity>\n</code></pre>\n\n<p>However, since a customer can change the quantity with the WooCommerce input-field, we need a way to get the current value of this field.</p>\n\n<p>So we have multiple options here, </p>\n\n<ul>\n<li><p>listen to an on-change event on the quantity field to update our URL, </p></li>\n<li><p>or append the current value of the quantity field to the URL, only\nif our custom button is clicked.</p></li>\n</ul>\n\n<p>The following code uses the second approach, only when the button is clicked the parameter gets added.</p>\n\n<p>Inside the <code>if( $product->is_type( 'simple' ) )</code> function, before the echo, enter this script:</p>\n\n<pre><code><script>\n jQuery(function($) {\n <?php /* if our custom button is clicked, append the string \"&quantity=\", and also the quantitiy number to the URL */ ?>\n\n // if our custom button is clicked\n $(\".custom-checkout-btn\").on(\"click\", function() {\n\n // get the value of the \"href\" attribute \n $(this).attr(\"href\", function() {\n // return the \"href\" value + the string \"&quantity=\" + the current selected quantity number\n return this.href + '&quantity=' + $('input.qty').val();\n });\n\n });\n });\n </script>\n</code></pre>\n\n<p>I did not included stop and start PHP tags in the code above! So you need to end PHP before the (?>) and start it again after the script (</p>\n"
},
{
"answer_id": 345525,
"author": "Afnan abbasi",
"author_id": 144224,
"author_profile": "https://wordpress.stackexchange.com/users/144224",
"pm_score": 0,
"selected": false,
"text": "<p>Just came here to paste my code, which has helped me solve my client's problem of having two buttons, one for checkout and one for add to cart. I have used a different approach and it helps with Variable products as well.</p>\n\n<pre><code>function wpcoderpro_direct_checkout_button() {\nglobal $product;\n$id = $product->get_id();\nif( $product->is_type( 'variable' ) ){\n echo '\n<script>\njQuery(document).ready(function($){\n $(\".redirect_to_checkout\").click(function(){\n $(\"button.single_add_to_cart_button \").click();\n window.location.href=\"/checkout/\";\n });\n});\n</script>\n<div class=\"button alt redirect_to_checkout\" style=\"cursor:pointer;\">CHECKOUT</div>\n';\n}\nelseif( $product->is_type( 'simple' ) ){\n echo '\n<script>\njQuery(document).ready(function($){\n$(\".input-text.qty\").change(function(){\n $(\".redirect_to_checkout a\").attr(\"href\", \"/checkout/?add-to-cart='. $id .'\" + \"&quantity= \" + $(this).val());\n});\n});\n</script>\n<div class=\"button alt redirect_to_checkout\" style=\"cursor:pointer;\"><a href=\"/checkout/?add-to-cart='. $id .'\">CHECKOUT</a></div>\n';\n}\n}\nadd_action( 'woocommerce_after_add_to_cart_button', 'wpcoderpro_direct_checkout_button', 20 );\n</code></pre>\n\n<p>Please do note that I use a plugin for AJAX Add to cart for Variable products, and I do not use AJAX Add to cart on Simple Products.</p>\n\n<p>The code goes to the function.php file of your child theme. Let me know if you need an explanation :)</p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7730/"
]
| I am trying to find a function which will add **ADDITIONAL** button next to the standard "Add to cart" button in woo commerce product page.
1. I added a woocommerce folder into my childe theme in order to modify
single-product => add-to-cart => simple.php
2. Inside simple.php I found the standard "Add to cart" button and after it is
where I want to add my custom additional "checkout" button
I found this function:
```
function woo_redirect_to_checkout() {
$checkout_url = WC()->cart->get_checkout_url();
return $checkout_url;
}
```
Which works fine BUT it modify ALL "add to cart" buttons in the site
and I am trying to add it ONLY to the new custom button that I am trying to add
(The new checkout button)
I managed to add a button which redirects to checkout page but doesn't Add the item to the cart prior to going to the checkout
Anyone knows how do I add a NEW button + this button needs to not only go to the checkout page but also trigger the "Add to cart" action at the same time
Thanks | You dont need to modify your template files for this, instead you can use the WooCommerce hook `woocommerce_after_add_to_cart_button`. This hook will add content after the "Add to cart" button.
If the customer clicks on this button, the product should get added to the cart, and the customer should be send to the checkout page, right?!
Basically you can add products to the cart with a link like this:
```
http://example.com/cart/?add-to-cart=<product ID>
```
So, using the hook mentioned above, and keeping this URL in mind, we can add a second button with this snippet:
```
function add_content_after_addtocart() {
// get the current post/product ID
$current_product_id = get_the_ID();
// get the product based on the ID
$product = wc_get_product( $current_product_id );
// get the "Checkout Page" URL
$checkout_url = WC()->cart->get_checkout_url();
// run only on simple products
if( $product->is_type( 'simple' ) ){
echo '<a href="'.$checkout_url.'?add-to-cart='.$current_product_id.'" class="single_add_to_cart_button button alt">Checkout</a>';
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
```
This will add a button after the normal Add to cart button on single product pages.
As you can see I also added a check to see if the current product is a simple product or not. If you want to use this with variation, it is more difficult.
With these products you need to generate an URL like:
```
http://example.com/cart/?add-to-cart=123&variation_id=456&attribute_pa_colour=black
```
---
Maybe you also need to check the default WooCommerce option `Enable AJAX Add to cart` (WooCommerce > Products > Display). I have not tested it with this setting.
---
**Update** to include the quantity
If you want to add a quantity you can also append a parameter to our button URL, like so:
```
http://example.com/cart/?add-to-cart=<product ID>&quantity=<number of quantity>
```
However, since a customer can change the quantity with the WooCommerce input-field, we need a way to get the current value of this field.
So we have multiple options here,
* listen to an on-change event on the quantity field to update our URL,
* or append the current value of the quantity field to the URL, only
if our custom button is clicked.
The following code uses the second approach, only when the button is clicked the parameter gets added.
Inside the `if( $product->is_type( 'simple' ) )` function, before the echo, enter this script:
```
<script>
jQuery(function($) {
<?php /* if our custom button is clicked, append the string "&quantity=", and also the quantitiy number to the URL */ ?>
// if our custom button is clicked
$(".custom-checkout-btn").on("click", function() {
// get the value of the "href" attribute
$(this).attr("href", function() {
// return the "href" value + the string "&quantity=" + the current selected quantity number
return this.href + '&quantity=' + $('input.qty').val();
});
});
});
</script>
```
I did not included stop and start PHP tags in the code above! So you need to end PHP before the (?>) and start it again after the script ( |
271,622 | <p>Say I wanted to add a site-wide snippet of JavaScript to my website but was using a child theme so as to not tamper with the original theme. Would I have to add a new .js file to the child theme, or could the script go into functions.php? Or, even better, could it be added with a plugin?</p>
| [
{
"answer_id": 271624,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 0,
"selected": false,
"text": "<p>Yes.</p>\n\n<p>Add the javascript file to the folder and call <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> with the proper filename. You can do this either in the child theme or a plugin, it really does not matter (from a technical perspective).</p>\n\n<p>If you aren't adding more functionality, I would not create a custom plugin for this and just include it within the child theme's function.php.</p>\n"
},
{
"answer_id": 271626,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 2,
"selected": false,
"text": "<p>You can do different things:</p>\n\n<ol>\n<li><strong>Enqueue</strong> the new JS file via <code>plugin</code></li>\n<li><strong>Enqueue</strong> the new JS file via <code>functions.php</code></li>\n<li>Add your JS code into <code>functions.php</code> through <code>wp_header</code> or <code>wp_footer</code></li>\n</ol>\n\n<p>For adding new JS files to a wordpress site you should <strong>enqueue</strong> these files with <code>wp_enqueue_style()</code> and/or <code>wp_enqueue_script()</code>. </p>\n\n<p>This is the proper and safest way.</p>\n\n<p>I would go the route and create a simple, small plugin for that, because this is theme independent.</p>\n\n<p>You <em>could</em> also use an hook to <code>wp_header</code> or <code>wp_footer</code>. Inside this hook you can write your JS code.</p>\n\n<p>But the proper way is enqueueing these files which will work something like this:</p>\n\n<pre><code>function prfx_frontend_enqueue() {\n wp_enqueue_style( 'my-plugin-css', plugins_url('/assets/css/plugin.css', __FILE__) );\n wp_enqueue_script( 'my-plugin-js', plugins_url('/assets/js/jquery.my-script-min.js', __FILE__), array('jquery'));\n}\nadd_action('wp_enqueue_scripts', 'prfx_frontend_enqueue');\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120427/"
]
| Say I wanted to add a site-wide snippet of JavaScript to my website but was using a child theme so as to not tamper with the original theme. Would I have to add a new .js file to the child theme, or could the script go into functions.php? Or, even better, could it be added with a plugin? | You can do different things:
1. **Enqueue** the new JS file via `plugin`
2. **Enqueue** the new JS file via `functions.php`
3. Add your JS code into `functions.php` through `wp_header` or `wp_footer`
For adding new JS files to a wordpress site you should **enqueue** these files with `wp_enqueue_style()` and/or `wp_enqueue_script()`.
This is the proper and safest way.
I would go the route and create a simple, small plugin for that, because this is theme independent.
You *could* also use an hook to `wp_header` or `wp_footer`. Inside this hook you can write your JS code.
But the proper way is enqueueing these files which will work something like this:
```
function prfx_frontend_enqueue() {
wp_enqueue_style( 'my-plugin-css', plugins_url('/assets/css/plugin.css', __FILE__) );
wp_enqueue_script( 'my-plugin-js', plugins_url('/assets/js/jquery.my-script-min.js', __FILE__), array('jquery'));
}
add_action('wp_enqueue_scripts', 'prfx_frontend_enqueue');
``` |
271,625 | <p>I am able to download a file in csv format for my table , but how to add column headers to the same file . </p>
<p>The current code is following -</p>
<pre><code>// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
</code></pre>
| [
{
"answer_id": 271635,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 1,
"selected": false,
"text": "<p>You should build Your columns schemat in array. Than add this on the top of csv and than You can add content of Your csv.</p>\n\n<pre><code>$string_headers = 'post_title,post_author,etc....';\n\nif(count($results) > 0)\n{\n $result = $string_header;\n foreach($results as $result){\n $tmp_result = array_values($result);\n $result .= implode(\", \", $tmp_result);\n $csv_output .= $result.\"\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 271707,
"author": "Divyanshu Jimmy",
"author_id": 92345,
"author_profile": "https://wordpress.stackexchange.com/users/92345",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to do it by first getting column names and then assigning it to final output : </p>\n\n<pre><code> $table_name = $wpdb->prefix.$_POST[\"table_name\"];// table name\n $file = 'database_csv'; // csv file name\n $results = $wpdb->get_results(\"SELECT * FROM $table_name\",ARRAY_A );\n\n // get column names\n $query = \"SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='\".$wpdb->dbname.\"' AND `TABLE_NAME`='\".$table_name.\"'\";\n\n $columnNamesList = $wpdb->get_results($query); \n\n\n foreach ( $columnNamesList as $column_name ) {\n $csv_output.=$column_name->COLUMN_NAME.\",\";\n }\n\n\n // remove last additional comma \n $csv_output = substr($csv_output,0,strlen($csv_output)-1);\n\n // start dumping csv rows in new line\n $csv_output.=\"\\n\";\n\n if(count($results) > 0){\n foreach($results as $result){\n $result = array_values($result);\n $result = implode(\", \", $result);\n $csv_output .= $result.\"\\n\";\n }\n }\n\n $filename = $file.\"_\".date(\"Y-m-d_H-i\",time());\n header(\"Content-type: application/vnd.ms-excel\");\n header(\"Content-disposition: csv\" . date(\"Y-m-d\") . \".csv\");\n header( \"Content-disposition: filename=\".$filename.\".csv\");\n header(\"Pragma: no-cache\");\n header(\"Expires: 0\");\n print $csv_output;\n exit;\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271625",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92345/"
]
| I am able to download a file in csv format for my table , but how to add column headers to the same file .
The current code is following -
```
// load wpdb
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
global $wpdb;
$table = $_POST["table_name"];// table name
$file = 'database_csv'; // csv file name
$results = $wpdb->get_results("SELECT * FROM $wpdb->prefix$table",ARRAY_A );
if(count($results) > 0){
foreach($results as $result){
$result = array_values($result);
$result = implode(", ", $result);
$csv_output .= $result."\n";
}
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output;
exit;
``` | You should build Your columns schemat in array. Than add this on the top of csv and than You can add content of Your csv.
```
$string_headers = 'post_title,post_author,etc....';
if(count($results) > 0)
{
$result = $string_header;
foreach($results as $result){
$tmp_result = array_values($result);
$result .= implode(", ", $tmp_result);
$csv_output .= $result."\n";
}
``` |
271,628 | <p>I am trying to customize the search results for a generic search, but <strong>only</strong> if it's using the <code>search.php</code> template. I have other searches on my site, and I don't want this filter interfering with them. Everything works on the following code, except for <code>is_page_template('search.php')</code>. </p>
<p>Once I enter that line of code as a condition, it just reverts to the normal search filtering, because my IF condition is failing. How do I only run my code if we're on the <code>search.php</code> page?</p>
<pre><code> //Filter the search for only posts and parts
function SearchFilter($query)
{
if ($query->is_search && is_page_template('search')) {
$query->set('post_type', array('post', 'parts'));
$query->set('meta_key', 'Manufacturer');
$query->set('orderby', 'meta_value');
$query->set('order', 'ASC');
}
return $query;
}
add_filter('pre_get_posts', 'SearchFilter');
</code></pre>
| [
{
"answer_id": 271632,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>There is a workaround that might cost you an extra query. However, @Milo once mentioned that WordPress is pretty smart about caching the queries, so this shouldn't be a big deal for you.</p>\n\n<p>You can run the query inside the <code>pre_get_posts</code> and then do some checks. If the situation matched your requirements, then filter the query:</p>\n\n<pre><code>//Filter the search for only posts and parts\nfunction SearchFilter($query)\n{\n remove_action('pre_get_posts', 'SearchFilter');\n // Run the query to fetch the results\n $posts = get_posts( $query->query );\n if(!empty($posts)) {\n // Check the template for the first post \n if( get_page_template_slug( $posts[0]->ID ) == 'YOUR SLUG HERE' ){\n $search_template = true; \n } else {\n $search_template = false; \n }\n }\n // Now filter the posts\n if ($query->is_main_query() & $query->is_search && $search_template) {\n $query->set('post_type', array('post', 'parts'));\n $query->set('meta_key', 'Manufacturer');\n $query->set('orderby', 'meta_value');\n $query->set('order', 'ASC');\n }\n return $query;\n}\n\nadd_action('pre_get_posts', 'SearchFilter');\n</code></pre>\n"
},
{
"answer_id": 271633,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>Lets break it down step by step:</p>\n\n<p><code>if ($query->is_search && is_page_template('search')) {</code></p>\n\n<p>There are 3 problems here</p>\n\n<h2><code>is_page_template</code></h2>\n\n<p><code>search.php</code> isn't a page template, that's not how the search template is loaded. So this won't work.</p>\n\n<p>But if it did work, there's a new problem. Functions such as <code>is_page_template</code> etc rely on the main query, but we're in a <code>pre_get_posts</code> filter, you don't know if that query has been set yet, or if you're filtering that query or another.</p>\n\n<p>So we need to:</p>\n\n<ul>\n<li>remove the <code>is_page_template</code> check, it doesn't do what you think it does</li>\n<li>Add an <code>$query->is_main_query()</code> check so the filter doesn't interfere with widgets and other queries</li>\n</ul>\n\n<h2>Methods vs member variables</h2>\n\n<p><code>if ($query->is_search</code></p>\n\n<p>This doesn't work, and should be generating PHP warnings for you. The problem is that <code>is_search</code> is a function/method not a variable, it should be:</p>\n\n<p><code>if ( $query->is_search() && $query->is_main_query() ) {</code></p>\n\n<h2>But <code>search.php</code>?</h2>\n\n<p>WordPress decides which template is loaded based on the main query. If it's the main query, and <code>is_search</code> is true, then <code>search.php</code> will be loaded.</p>\n\n<p>Because of this, WordPress hasn't decided which template to use when your filter happens. In fact, you can make WordPress change which template it loads by modifying the query variables. For example, if you unset all the variables, and tell it to load a single post, you won't get <code>search.php</code>, or an archive at all, you're likely to get <code>single.php</code> instead</p>\n\n<h2>What About Search Queries in Page Templates?</h2>\n\n<p><code>is_main_query</code> will be false, so not an issue</p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94213/"
]
| I am trying to customize the search results for a generic search, but **only** if it's using the `search.php` template. I have other searches on my site, and I don't want this filter interfering with them. Everything works on the following code, except for `is_page_template('search.php')`.
Once I enter that line of code as a condition, it just reverts to the normal search filtering, because my IF condition is failing. How do I only run my code if we're on the `search.php` page?
```
//Filter the search for only posts and parts
function SearchFilter($query)
{
if ($query->is_search && is_page_template('search')) {
$query->set('post_type', array('post', 'parts'));
$query->set('meta_key', 'Manufacturer');
$query->set('orderby', 'meta_value');
$query->set('order', 'ASC');
}
return $query;
}
add_filter('pre_get_posts', 'SearchFilter');
``` | Lets break it down step by step:
`if ($query->is_search && is_page_template('search')) {`
There are 3 problems here
`is_page_template`
------------------
`search.php` isn't a page template, that's not how the search template is loaded. So this won't work.
But if it did work, there's a new problem. Functions such as `is_page_template` etc rely on the main query, but we're in a `pre_get_posts` filter, you don't know if that query has been set yet, or if you're filtering that query or another.
So we need to:
* remove the `is_page_template` check, it doesn't do what you think it does
* Add an `$query->is_main_query()` check so the filter doesn't interfere with widgets and other queries
Methods vs member variables
---------------------------
`if ($query->is_search`
This doesn't work, and should be generating PHP warnings for you. The problem is that `is_search` is a function/method not a variable, it should be:
`if ( $query->is_search() && $query->is_main_query() ) {`
But `search.php`?
-----------------
WordPress decides which template is loaded based on the main query. If it's the main query, and `is_search` is true, then `search.php` will be loaded.
Because of this, WordPress hasn't decided which template to use when your filter happens. In fact, you can make WordPress change which template it loads by modifying the query variables. For example, if you unset all the variables, and tell it to load a single post, you won't get `search.php`, or an archive at all, you're likely to get `single.php` instead
What About Search Queries in Page Templates?
--------------------------------------------
`is_main_query` will be false, so not an issue |
271,661 | <p>My loop displays featured posts and then posts in reverse chronological order. </p>
<p>However when I use <code><?php echo get_previous_post(); ?></code> it grabs posts in reverse chronological order.</p>
<p>How do I add a filter to the previous post function similiar to <a href="https://wordpress.stackexchange.com/questions/194597/how-can-i-get-next-previous-post-links-to-order-by-a-filter-by-the-last-word-o">this</a> but instead filter by an array like this: <code>'orderby' => array( 'meta_value' =>
'DESC', 'date' => 'DESC')</code> ?</p>
<hr/>
<p><strong>Code:</strong> </p>
<hr>
<p><strong>UPDATE:</strong> Cleaned up index.php loop after help from @sMyles and @JackJohansson</p>
<p><em>Index.php loop:</em></p>
<pre><code>$args = array(
'posts_per_page' => - 1,
'meta_key' => 'meta-checkbox',
'orderby' => array( 'meta_value' => 'DESC', 'date' => 'DESC')
);
$posts = new WP_Query( $args );
if($posts->have_posts() ){
while( $posts->have_posts() ){
$posts->the_post();
// Set to content template by default
$template = 'content';
// Change template to featured when `is_featured` meta has a value
if(get_post_meta(get_the_ID(), 'meta-checkbox', 'yes')){
$template = 'featured';
}
// Load template part
get_template_part( $template, get_post_format() );
}
}
</code></pre>
<p><hr>
<strong>UPDATE:</strong> As suggested, I added where I use the previous post function</p>
<p><em>Previous Post Function</em></p>
<pre><code><div id="next-post">
<?php $prev_post = get_previous_post();
if(!empty($prev_post)) {
echo '<a class="next-story" href="' . get_permalink($prev_post->ID) . '">Next Story</a>';
echo '<a class="next-story-title" href="' . get_permalink($prev_post->ID) . '" title="' . $prev_post->post_title . '">' . $prev_post->post_title . '</a>';
} ?>
</div>
</code></pre>
<p><hr>
<em>Function For Featured Posts:</em></p>
<pre><code>function sm_custom_meta() {
add_meta_box( 'sm_meta', __( 'Featured Posts', 'sm-textdomain' ), 'sm_meta_callback', 'post' );
}
function sm_meta_callback( $post ) {
$featured = get_post_meta( $post->ID );
?>
<p>
<div class="sm-row-content">
<label for="meta-checkbox">
<input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $featured['meta-checkbox'] ) ) checked( $featured['meta-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Featured this post', 'sm-textdomain' )?>
</label>
</div>
</p>
<?php
}
add_action( 'add_meta_boxes', 'sm_custom_meta' );
function sm_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'sm_nonce' ] ) && wp_verify_nonce( $_POST[ 'sm_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox' ] ) ) {
update_post_meta( $post_id, 'meta-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'meta-checkbox', '' );
}
}
add_action( 'save_post', 'sm_meta_save' );
</code></pre>
| [
{
"answer_id": 271632,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>There is a workaround that might cost you an extra query. However, @Milo once mentioned that WordPress is pretty smart about caching the queries, so this shouldn't be a big deal for you.</p>\n\n<p>You can run the query inside the <code>pre_get_posts</code> and then do some checks. If the situation matched your requirements, then filter the query:</p>\n\n<pre><code>//Filter the search for only posts and parts\nfunction SearchFilter($query)\n{\n remove_action('pre_get_posts', 'SearchFilter');\n // Run the query to fetch the results\n $posts = get_posts( $query->query );\n if(!empty($posts)) {\n // Check the template for the first post \n if( get_page_template_slug( $posts[0]->ID ) == 'YOUR SLUG HERE' ){\n $search_template = true; \n } else {\n $search_template = false; \n }\n }\n // Now filter the posts\n if ($query->is_main_query() & $query->is_search && $search_template) {\n $query->set('post_type', array('post', 'parts'));\n $query->set('meta_key', 'Manufacturer');\n $query->set('orderby', 'meta_value');\n $query->set('order', 'ASC');\n }\n return $query;\n}\n\nadd_action('pre_get_posts', 'SearchFilter');\n</code></pre>\n"
},
{
"answer_id": 271633,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": false,
"text": "<p>Lets break it down step by step:</p>\n\n<p><code>if ($query->is_search && is_page_template('search')) {</code></p>\n\n<p>There are 3 problems here</p>\n\n<h2><code>is_page_template</code></h2>\n\n<p><code>search.php</code> isn't a page template, that's not how the search template is loaded. So this won't work.</p>\n\n<p>But if it did work, there's a new problem. Functions such as <code>is_page_template</code> etc rely on the main query, but we're in a <code>pre_get_posts</code> filter, you don't know if that query has been set yet, or if you're filtering that query or another.</p>\n\n<p>So we need to:</p>\n\n<ul>\n<li>remove the <code>is_page_template</code> check, it doesn't do what you think it does</li>\n<li>Add an <code>$query->is_main_query()</code> check so the filter doesn't interfere with widgets and other queries</li>\n</ul>\n\n<h2>Methods vs member variables</h2>\n\n<p><code>if ($query->is_search</code></p>\n\n<p>This doesn't work, and should be generating PHP warnings for you. The problem is that <code>is_search</code> is a function/method not a variable, it should be:</p>\n\n<p><code>if ( $query->is_search() && $query->is_main_query() ) {</code></p>\n\n<h2>But <code>search.php</code>?</h2>\n\n<p>WordPress decides which template is loaded based on the main query. If it's the main query, and <code>is_search</code> is true, then <code>search.php</code> will be loaded.</p>\n\n<p>Because of this, WordPress hasn't decided which template to use when your filter happens. In fact, you can make WordPress change which template it loads by modifying the query variables. For example, if you unset all the variables, and tell it to load a single post, you won't get <code>search.php</code>, or an archive at all, you're likely to get <code>single.php</code> instead</p>\n\n<h2>What About Search Queries in Page Templates?</h2>\n\n<p><code>is_main_query</code> will be false, so not an issue</p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122778/"
]
| My loop displays featured posts and then posts in reverse chronological order.
However when I use `<?php echo get_previous_post(); ?>` it grabs posts in reverse chronological order.
How do I add a filter to the previous post function similiar to [this](https://wordpress.stackexchange.com/questions/194597/how-can-i-get-next-previous-post-links-to-order-by-a-filter-by-the-last-word-o) but instead filter by an array like this: `'orderby' => array( 'meta_value' =>
'DESC', 'date' => 'DESC')` ?
---
**Code:**
---
**UPDATE:** Cleaned up index.php loop after help from @sMyles and @JackJohansson
*Index.php loop:*
```
$args = array(
'posts_per_page' => - 1,
'meta_key' => 'meta-checkbox',
'orderby' => array( 'meta_value' => 'DESC', 'date' => 'DESC')
);
$posts = new WP_Query( $args );
if($posts->have_posts() ){
while( $posts->have_posts() ){
$posts->the_post();
// Set to content template by default
$template = 'content';
// Change template to featured when `is_featured` meta has a value
if(get_post_meta(get_the_ID(), 'meta-checkbox', 'yes')){
$template = 'featured';
}
// Load template part
get_template_part( $template, get_post_format() );
}
}
```
---
**UPDATE:** As suggested, I added where I use the previous post function
*Previous Post Function*
```
<div id="next-post">
<?php $prev_post = get_previous_post();
if(!empty($prev_post)) {
echo '<a class="next-story" href="' . get_permalink($prev_post->ID) . '">Next Story</a>';
echo '<a class="next-story-title" href="' . get_permalink($prev_post->ID) . '" title="' . $prev_post->post_title . '">' . $prev_post->post_title . '</a>';
} ?>
</div>
```
---
*Function For Featured Posts:*
```
function sm_custom_meta() {
add_meta_box( 'sm_meta', __( 'Featured Posts', 'sm-textdomain' ), 'sm_meta_callback', 'post' );
}
function sm_meta_callback( $post ) {
$featured = get_post_meta( $post->ID );
?>
<p>
<div class="sm-row-content">
<label for="meta-checkbox">
<input type="checkbox" name="meta-checkbox" id="meta-checkbox" value="yes" <?php if ( isset ( $featured['meta-checkbox'] ) ) checked( $featured['meta-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Featured this post', 'sm-textdomain' )?>
</label>
</div>
</p>
<?php
}
add_action( 'add_meta_boxes', 'sm_custom_meta' );
function sm_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'sm_nonce' ] ) && wp_verify_nonce( $_POST[ 'sm_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves
if( isset( $_POST[ 'meta-checkbox' ] ) ) {
update_post_meta( $post_id, 'meta-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'meta-checkbox', '' );
}
}
add_action( 'save_post', 'sm_meta_save' );
``` | Lets break it down step by step:
`if ($query->is_search && is_page_template('search')) {`
There are 3 problems here
`is_page_template`
------------------
`search.php` isn't a page template, that's not how the search template is loaded. So this won't work.
But if it did work, there's a new problem. Functions such as `is_page_template` etc rely on the main query, but we're in a `pre_get_posts` filter, you don't know if that query has been set yet, or if you're filtering that query or another.
So we need to:
* remove the `is_page_template` check, it doesn't do what you think it does
* Add an `$query->is_main_query()` check so the filter doesn't interfere with widgets and other queries
Methods vs member variables
---------------------------
`if ($query->is_search`
This doesn't work, and should be generating PHP warnings for you. The problem is that `is_search` is a function/method not a variable, it should be:
`if ( $query->is_search() && $query->is_main_query() ) {`
But `search.php`?
-----------------
WordPress decides which template is loaded based on the main query. If it's the main query, and `is_search` is true, then `search.php` will be loaded.
Because of this, WordPress hasn't decided which template to use when your filter happens. In fact, you can make WordPress change which template it loads by modifying the query variables. For example, if you unset all the variables, and tell it to load a single post, you won't get `search.php`, or an archive at all, you're likely to get `single.php` instead
What About Search Queries in Page Templates?
--------------------------------------------
`is_main_query` will be false, so not an issue |
271,662 | <p>I have a subdomain multisite network. I have implemented a system in order to create new subdomains programmatically, just filling a form.</p>
<p>Now I have a need: when a new blog is created, I'd like to set its permalink structure to /postname/.</p>
<p>I've tried these solutions:</p>
<p><strong><a href="https://wordpress.stackexchange.com/questions/31207/how-to-set-permalink-structure-via-functions-php">How to set permalink structure via functions.php</a></strong></p>
<pre><code>function set_default_permalink_for_new_blogs($blog_id)
{
global $wp_rewrite;
$wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%postname%/' );
}
add_action('wpmu_activate_blog', 'set_default_permalink_for_new_blogs');
</code></pre>
<p>I've added this snippet in the functions.php of the theme used for the main site, where the system above mentioned is. It simply doesn't work.</p>
<p><strong><a href="https://wordpress.stackexchange.com/questions/36306/how-do-i-programmatically-force-custom-permalinks-with-my-theme">How Do I Programmatically Force Custom Permalinks with My Theme?</a></strong></p>
<pre><code>function change_permalinks() {
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
}
add_action('init', 'change_permalinks');
</code></pre>
<p>I have some concerns with this snippet: I don't think it could be a good idea to fire the rewrite on every "init" (also someone else expressed doubt about this in comments); in second place, this snippet has to be placed on the default theme of new blogs - but what if I want to change the default theme in future?</p>
<p>Thank you very much for every suggestions,</p>
<p>Marco</p>
| [
{
"answer_id": 271665,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to create an mu-plugin (required plugin) that fires on the <code>activate_blog</code> hook. Something like this should get you started in the right direction:</p>\n\n<pre><code><?php\n/* Plugin name: WPSE Permalink Setter\nDescription: Sets permalink structure for each blog activation\n*/\nadd_action('activate_blog', 'wpse_271662_set_permalinks');\nfunction wpse_271662_set_permalinks() {\n global $wp_rewrite;\n $wp_rewrite->set_permalink_structure('/%postname%/');\n $wp_rewrite->flush_rules();\n}\n?>\n</code></pre>\n\n<p>Since the code only runs when a new site is created (<code>activate_blog</code>), this prevents performance issues associated with running on every <code>init</code>, and it doesn't rely on a theme. Of course in theory, site admins could change the permalink structure later, but this would give them a clean install with the permalink structure you want, unless they monkey around with it.</p>\n\n<p>Place this file directly inside <code>/wp-content/mu-plugins/</code> (no subfolder like normal plugins) so it will run automatically unless the file is deleted.</p>\n"
},
{
"answer_id": 290599,
"author": "José Machado",
"author_id": 134542,
"author_profile": "https://wordpress.stackexchange.com/users/134542",
"pm_score": 3,
"selected": true,
"text": "<p>With a \"mu-plugins\", the solution is...</p>\n\n<pre><code>add_action( 'wpmu_new_blog', function( $blog_id ){\n\nswitch_to_blog( $blog_id );\nglobal $wp_rewrite;\n$wp_rewrite->set_permalink_structure('/%postname%/');\n$wp_rewrite->flush_rules();\nrestore_current_blog();\n\n}, 10 );\n</code></pre>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32321/"
]
| I have a subdomain multisite network. I have implemented a system in order to create new subdomains programmatically, just filling a form.
Now I have a need: when a new blog is created, I'd like to set its permalink structure to /postname/.
I've tried these solutions:
**[How to set permalink structure via functions.php](https://wordpress.stackexchange.com/questions/31207/how-to-set-permalink-structure-via-functions-php)**
```
function set_default_permalink_for_new_blogs($blog_id)
{
global $wp_rewrite;
$wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%postname%/' );
}
add_action('wpmu_activate_blog', 'set_default_permalink_for_new_blogs');
```
I've added this snippet in the functions.php of the theme used for the main site, where the system above mentioned is. It simply doesn't work.
**[How Do I Programmatically Force Custom Permalinks with My Theme?](https://wordpress.stackexchange.com/questions/36306/how-do-i-programmatically-force-custom-permalinks-with-my-theme)**
```
function change_permalinks() {
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
}
add_action('init', 'change_permalinks');
```
I have some concerns with this snippet: I don't think it could be a good idea to fire the rewrite on every "init" (also someone else expressed doubt about this in comments); in second place, this snippet has to be placed on the default theme of new blogs - but what if I want to change the default theme in future?
Thank you very much for every suggestions,
Marco | With a "mu-plugins", the solution is...
```
add_action( 'wpmu_new_blog', function( $blog_id ){
switch_to_blog( $blog_id );
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
restore_current_blog();
}, 10 );
``` |
271,672 | <p>I want my WP <strong>default gallery</strong> to go from 4 columns on computer screens down to 2 on mobile devices.</p>
| [
{
"answer_id": 271675,
"author": "DigitalDesigner",
"author_id": 111895,
"author_profile": "https://wordpress.stackexchange.com/users/111895",
"pm_score": 3,
"selected": true,
"text": "<p>You can try using css to control the visual layout.</p>\n\n<p>I have tested on my dev server and this was successful.</p>\n\n<pre><code> @media only screen and ( max-width: 320px ) {\n .gallery-item {float:left;width:50% !important;}\n }\n</code></pre>\n\n<p>what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.</p>\n\n<p>Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.</p>\n\n<p>Try it out and hope it helps.</p>\n"
},
{
"answer_id": 302805,
"author": "Jim Kinney",
"author_id": 128977,
"author_profile": "https://wordpress.stackexchange.com/users/128977",
"pm_score": 0,
"selected": false,
"text": "<p>The secret to a responsive gallery is to not specify a column number. This will make it display gallery items until the items spill to the next line. Make sure gallery items are set to \"display: inline-block.\"<img src=\"https://i.stack.imgur.com/6dXx8.jpg\" alt=\"3 items will fit on an iphone x because I didn't set the # of columns on my clients site.\"></p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122774/"
]
| I want my WP **default gallery** to go from 4 columns on computer screens down to 2 on mobile devices. | You can try using css to control the visual layout.
I have tested on my dev server and this was successful.
```
@media only screen and ( max-width: 320px ) {
.gallery-item {float:left;width:50% !important;}
}
```
what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.
Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.
Try it out and hope it helps. |
271,677 | <p><strong>Short description:</strong> I've created a bunch of terms and attached them to an existing taxonomy for a certain custom-post that already exist using the SQL code below. After doing this I'd like to update wp_term_taxonomy.count . I set it to 0 (dumb?) so the new terms are not appearing in search forms (they do appear on the individual custom post though). Setting count to 1 fixes this but still 'wrong' and I'm worried this could cause issues down the line.</p>
<p>Answers within SQL or Wordpress will work though my coding is just above n00b status. </p>
<p><strong>My solution:</strong> set wp_term_taxonomy.count to 1 for new terms so it'll appear across the site. I can use them in searches (important) but things like tag clouds are wrong/mis-sized (fine) and I'm worried I'll run into unknown issues.</p>
<p><strong>Details:</strong>
I am adding many terms to a taxonomy I have already created called 'csf_brand' for a custom post type called 'jeans'. Rather than editing each of several hundred custom posts already created I thought I'd batch them with SQL, using the 3 tables related to custom taxonomies. </p>
<p>First I create my new terms.</p>
<pre><code>INSERT INTO `wp_nhyb_terms` (`term_id`, `name`, `slug`, `term_group`) VALUES
(10, 'GAP', 'gap', 0); --there's a bunch more lines like this adding in new terms
</code></pre>
<p>Next, I attach my terms to the appropriate taxonomy. 0 is not the right count but calculating this is not something I'm interested in doing if I can avoid it. </p>
<pre><code>INSERT INTO `wp_nhyb_term_taxonomy` (`term_taxonomy_id`, `term_id`, `taxonomy`, `description`, `parent`, `count`) VALUES
(10, 10, 'csf_brand', '', 0, 0); --Here is where I could use 1 instead of 0
</code></pre>
<p>Finally, I attach the terms to my custom post types by the post ID (object_id)</p>
<pre><code>INSERT INTO `wp_nhyb_term_relationships` (`object_id`, `term_taxonomy_id`, `term_order`) VALUES
(125, 10, 0);
</code></pre>
<p>And that works. But wp_term_taxonomy.count is not 0 so they aren't appearing in my searches (e.g. I have a page that can search for brands via dropdown and they aren't an option). If I edit a custom post in my browser then save it recognizes the new term and corrects the count. But that's not a great process since I'll eventually miss something. </p>
| [
{
"answer_id": 271675,
"author": "DigitalDesigner",
"author_id": 111895,
"author_profile": "https://wordpress.stackexchange.com/users/111895",
"pm_score": 3,
"selected": true,
"text": "<p>You can try using css to control the visual layout.</p>\n\n<p>I have tested on my dev server and this was successful.</p>\n\n<pre><code> @media only screen and ( max-width: 320px ) {\n .gallery-item {float:left;width:50% !important;}\n }\n</code></pre>\n\n<p>what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.</p>\n\n<p>Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.</p>\n\n<p>Try it out and hope it helps.</p>\n"
},
{
"answer_id": 302805,
"author": "Jim Kinney",
"author_id": 128977,
"author_profile": "https://wordpress.stackexchange.com/users/128977",
"pm_score": 0,
"selected": false,
"text": "<p>The secret to a responsive gallery is to not specify a column number. This will make it display gallery items until the items spill to the next line. Make sure gallery items are set to \"display: inline-block.\"<img src=\"https://i.stack.imgur.com/6dXx8.jpg\" alt=\"3 items will fit on an iphone x because I didn't set the # of columns on my clients site.\"></p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121811/"
]
| **Short description:** I've created a bunch of terms and attached them to an existing taxonomy for a certain custom-post that already exist using the SQL code below. After doing this I'd like to update wp\_term\_taxonomy.count . I set it to 0 (dumb?) so the new terms are not appearing in search forms (they do appear on the individual custom post though). Setting count to 1 fixes this but still 'wrong' and I'm worried this could cause issues down the line.
Answers within SQL or Wordpress will work though my coding is just above n00b status.
**My solution:** set wp\_term\_taxonomy.count to 1 for new terms so it'll appear across the site. I can use them in searches (important) but things like tag clouds are wrong/mis-sized (fine) and I'm worried I'll run into unknown issues.
**Details:**
I am adding many terms to a taxonomy I have already created called 'csf\_brand' for a custom post type called 'jeans'. Rather than editing each of several hundred custom posts already created I thought I'd batch them with SQL, using the 3 tables related to custom taxonomies.
First I create my new terms.
```
INSERT INTO `wp_nhyb_terms` (`term_id`, `name`, `slug`, `term_group`) VALUES
(10, 'GAP', 'gap', 0); --there's a bunch more lines like this adding in new terms
```
Next, I attach my terms to the appropriate taxonomy. 0 is not the right count but calculating this is not something I'm interested in doing if I can avoid it.
```
INSERT INTO `wp_nhyb_term_taxonomy` (`term_taxonomy_id`, `term_id`, `taxonomy`, `description`, `parent`, `count`) VALUES
(10, 10, 'csf_brand', '', 0, 0); --Here is where I could use 1 instead of 0
```
Finally, I attach the terms to my custom post types by the post ID (object\_id)
```
INSERT INTO `wp_nhyb_term_relationships` (`object_id`, `term_taxonomy_id`, `term_order`) VALUES
(125, 10, 0);
```
And that works. But wp\_term\_taxonomy.count is not 0 so they aren't appearing in my searches (e.g. I have a page that can search for brands via dropdown and they aren't an option). If I edit a custom post in my browser then save it recognizes the new term and corrects the count. But that's not a great process since I'll eventually miss something. | You can try using css to control the visual layout.
I have tested on my dev server and this was successful.
```
@media only screen and ( max-width: 320px ) {
.gallery-item {float:left;width:50% !important;}
}
```
what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.
Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.
Try it out and hope it helps. |
271,682 | <h2><strong>The Problem</strong></h2>
<p>So I installed a plugin (iHomeFinder's Optima Express), and it works perfectly fine. The page it made is
<a href="http://conradbowenrealestate.com/homes-for-sale-search/" rel="nofollow noreferrer">conradbowenrealestate.com/homes-for-sale-search</a>. However, this page isn't made in WordPress, it doesn't even exist to it. I want to make it the homepage, but since WordPress doesn't recognize it as a WP page, I can't set it as the homepage. <strong>Note that when viewing the source code, the "page-id" is 0.</strong></p>
<h2><strong>What I've Tried</strong></h2>
<p>I've tried using this code in the functions.php file, but it doesn't enact any change on the website:</p>
<pre><code>$homepage = get_page('0');
if ( $homepage )
{
update_option( 'page_on_front', $homepage->ID );
update_option( 'show_on_front', 'page' );
}
</code></pre>
<p>It does work if I change the ID to one of the pages listed in my WP-Admin's "Pages" section. <code>get_page_by_title</code> doesn't work since again, that's for WP pages and this is invisible to WP.</p>
<p>I've also tried recreating the object on the plugin page by going to the source code and copy/pasting it to my homepage's code. While it does work and is functional, it is out of proportions (too much space between options).</p>
<h2><strong>My Question</strong></h2>
<p>How can I get this search plugin on my homepage? I want the above mentioned plugin page to be what shows when you go to <a href="http://conradbowenrealestate.com/" rel="nofollow noreferrer">conradbowenrealestate.com</a>.</p>
<h2><strong>Edit:</strong></h2>
<p>I failed to mention that within the plugin settings, I am limited to: <a href="http://conradbowenrealestate.com/" rel="nofollow noreferrer">http://conradbowenrealestate.com/</a> [insert text here] /. If I leave it blank, it won't save.</p>
| [
{
"answer_id": 271675,
"author": "DigitalDesigner",
"author_id": 111895,
"author_profile": "https://wordpress.stackexchange.com/users/111895",
"pm_score": 3,
"selected": true,
"text": "<p>You can try using css to control the visual layout.</p>\n\n<p>I have tested on my dev server and this was successful.</p>\n\n<pre><code> @media only screen and ( max-width: 320px ) {\n .gallery-item {float:left;width:50% !important;}\n }\n</code></pre>\n\n<p>what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.</p>\n\n<p>Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.</p>\n\n<p>Try it out and hope it helps.</p>\n"
},
{
"answer_id": 302805,
"author": "Jim Kinney",
"author_id": 128977,
"author_profile": "https://wordpress.stackexchange.com/users/128977",
"pm_score": 0,
"selected": false,
"text": "<p>The secret to a responsive gallery is to not specify a column number. This will make it display gallery items until the items spill to the next line. Make sure gallery items are set to \"display: inline-block.\"<img src=\"https://i.stack.imgur.com/6dXx8.jpg\" alt=\"3 items will fit on an iphone x because I didn't set the # of columns on my clients site.\"></p>\n"
}
]
| 2017/06/28 | [
"https://wordpress.stackexchange.com/questions/271682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115413/"
]
| **The Problem**
---------------
So I installed a plugin (iHomeFinder's Optima Express), and it works perfectly fine. The page it made is
[conradbowenrealestate.com/homes-for-sale-search](http://conradbowenrealestate.com/homes-for-sale-search/). However, this page isn't made in WordPress, it doesn't even exist to it. I want to make it the homepage, but since WordPress doesn't recognize it as a WP page, I can't set it as the homepage. **Note that when viewing the source code, the "page-id" is 0.**
**What I've Tried**
-------------------
I've tried using this code in the functions.php file, but it doesn't enact any change on the website:
```
$homepage = get_page('0');
if ( $homepage )
{
update_option( 'page_on_front', $homepage->ID );
update_option( 'show_on_front', 'page' );
}
```
It does work if I change the ID to one of the pages listed in my WP-Admin's "Pages" section. `get_page_by_title` doesn't work since again, that's for WP pages and this is invisible to WP.
I've also tried recreating the object on the plugin page by going to the source code and copy/pasting it to my homepage's code. While it does work and is functional, it is out of proportions (too much space between options).
**My Question**
---------------
How can I get this search plugin on my homepage? I want the above mentioned plugin page to be what shows when you go to [conradbowenrealestate.com](http://conradbowenrealestate.com/).
**Edit:**
---------
I failed to mention that within the plugin settings, I am limited to: <http://conradbowenrealestate.com/> [insert text here] /. If I leave it blank, it won't save. | You can try using css to control the visual layout.
I have tested on my dev server and this was successful.
```
@media only screen and ( max-width: 320px ) {
.gallery-item {float:left;width:50% !important;}
}
```
what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.
Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.
Try it out and hope it helps. |
271,740 | <p>My website is currently on localhost but painfully slow.</p>
<p>I am going to upload it to <code>000webhost.com</code> who offer a free hosting service. I am keen to see if this speeds things up.</p>
<p>I was wondering if there is anything I need to do when uploading my website, taking off localhost and moving to <code>000webhost.com</code>.</p>
<p>Currently all files are saved in <code>WAMP</code> in a folder called <code>Wordpress</code>...</p>
<p>Should it be as simple as uploading this file to my new host?</p>
<p>I was also keen to hear if anyone could advise as to the best for products for backing up a wordpress site?</p>
<p>Thank you in advance.</p>
<p>Sorry, I meant to also ask, Is it a bad idea to upload to one host then move to another when I am setting it live as I was planning on going to 1&1 for setting the website live</p>
| [
{
"answer_id": 271675,
"author": "DigitalDesigner",
"author_id": 111895,
"author_profile": "https://wordpress.stackexchange.com/users/111895",
"pm_score": 3,
"selected": true,
"text": "<p>You can try using css to control the visual layout.</p>\n\n<p>I have tested on my dev server and this was successful.</p>\n\n<pre><code> @media only screen and ( max-width: 320px ) {\n .gallery-item {float:left;width:50% !important;}\n }\n</code></pre>\n\n<p>what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.</p>\n\n<p>Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.</p>\n\n<p>Try it out and hope it helps.</p>\n"
},
{
"answer_id": 302805,
"author": "Jim Kinney",
"author_id": 128977,
"author_profile": "https://wordpress.stackexchange.com/users/128977",
"pm_score": 0,
"selected": false,
"text": "<p>The secret to a responsive gallery is to not specify a column number. This will make it display gallery items until the items spill to the next line. Make sure gallery items are set to \"display: inline-block.\"<img src=\"https://i.stack.imgur.com/6dXx8.jpg\" alt=\"3 items will fit on an iphone x because I didn't set the # of columns on my clients site.\"></p>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122361/"
]
| My website is currently on localhost but painfully slow.
I am going to upload it to `000webhost.com` who offer a free hosting service. I am keen to see if this speeds things up.
I was wondering if there is anything I need to do when uploading my website, taking off localhost and moving to `000webhost.com`.
Currently all files are saved in `WAMP` in a folder called `Wordpress`...
Should it be as simple as uploading this file to my new host?
I was also keen to hear if anyone could advise as to the best for products for backing up a wordpress site?
Thank you in advance.
Sorry, I meant to also ask, Is it a bad idea to upload to one host then move to another when I am setting it live as I was planning on going to 1&1 for setting the website live | You can try using css to control the visual layout.
I have tested on my dev server and this was successful.
```
@media only screen and ( max-width: 320px ) {
.gallery-item {float:left;width:50% !important;}
}
```
what we have done is set the column to 50% the total container width when viewing on devices smaller then 320px. You can adjust this as you see fit.
Simply drop this styling into your themes css via your theme options page. If you do not have one you can also add it to the themes css stylesheet if you have admin access through Appearance > Editor.
Try it out and hope it helps. |
271,786 | <p>I have two WordPress websites on the same domain and on the same database.
All my accounts created on the first main website also works on the second website and is automatically logging in.</p>
<p>But the administrator isn't functioning anymore. If I sign up as administrator and go to the intranet website I should be able to see a button only visible by administrator, also the back-end is blocked for me.</p>
<p>I made sure both websites are installed on the same server and the second website is linked to the users and usermeta tables. Also made sure both hashcodes are both identical.
The following codes have been entered in the wp-config files:</p>
<p>Website <a href="https://www.pax-security.nl" rel="nofollow noreferrer">https://www.pax-security.nl</a></p>
<pre><code>define( 'COOKIE_DOMAIN', '.pax-security.nl' );
define( 'COOKIEPATH', '/' );
define( 'COOKIEHASH', md5( 'pax-security.nl' ) );
define( 'CUSTOM_USER_TABLE', 'wp_users' );
define( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' );
</code></pre>
<p>Website <a href="https://www.pax-security.nl/intranet" rel="nofollow noreferrer">https://www.pax-security.nl/intranet</a></p>
<pre><code>define( 'COOKIE_DOMAIN', '.pax-security.nl' );
define( 'COOKIEPATH', '/' );
define( 'COOKIEHASH', md5( 'pax-security.nl' ) );
define( 'CUSTOM_USER_TABLE', 'wp_users' );
define( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' );
</code></pre>
<p>Why is my administrator account on the first website an administrator account, while this same account is not an administrator account on the intranet website? I do am able to login with the same account in both websites.</p>
| [
{
"answer_id": 271792,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>User roles aren't stored in the user or user meta table, they have their own table, and they're on a per site basis so reusing them isn't so simple for setups like this.</p>\n\n<p>In your case it would be <strong>significantly</strong> easier to use a multisite install using subdirectories rather than subdomains, then all of this would be taken care of for you automatically.</p>\n"
},
{
"answer_id": 271794,
"author": "H. Rensenbrink",
"author_id": 122754,
"author_profile": "https://wordpress.stackexchange.com/users/122754",
"pm_score": 0,
"selected": false,
"text": "<p>Well the solution was kind of easy.\nUsually in the wp_usermeta you have the usual information for all accounts (administrator settings).</p>\n\n<p>wp_capabilities and wp_user_level\nJust needed to add the different prefix instead of the wp.</p>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122754/"
]
| I have two WordPress websites on the same domain and on the same database.
All my accounts created on the first main website also works on the second website and is automatically logging in.
But the administrator isn't functioning anymore. If I sign up as administrator and go to the intranet website I should be able to see a button only visible by administrator, also the back-end is blocked for me.
I made sure both websites are installed on the same server and the second website is linked to the users and usermeta tables. Also made sure both hashcodes are both identical.
The following codes have been entered in the wp-config files:
Website <https://www.pax-security.nl>
```
define( 'COOKIE_DOMAIN', '.pax-security.nl' );
define( 'COOKIEPATH', '/' );
define( 'COOKIEHASH', md5( 'pax-security.nl' ) );
define( 'CUSTOM_USER_TABLE', 'wp_users' );
define( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' );
```
Website <https://www.pax-security.nl/intranet>
```
define( 'COOKIE_DOMAIN', '.pax-security.nl' );
define( 'COOKIEPATH', '/' );
define( 'COOKIEHASH', md5( 'pax-security.nl' ) );
define( 'CUSTOM_USER_TABLE', 'wp_users' );
define( 'CUSTOM_USER_META_TABLE', 'wp_usermeta' );
```
Why is my administrator account on the first website an administrator account, while this same account is not an administrator account on the intranet website? I do am able to login with the same account in both websites. | User roles aren't stored in the user or user meta table, they have their own table, and they're on a per site basis so reusing them isn't so simple for setups like this.
In your case it would be **significantly** easier to use a multisite install using subdirectories rather than subdomains, then all of this would be taken care of for you automatically. |
271,814 | <p>In my projects I have some components which I use in a lot of custom Plugins as well as in some custom coded Themes like e.g. admin image or video selectors.</p>
<p>Those I am holding in custom git repositories. However as those components are used in both - themes and plugins - I always have to manually change the URL getters after pulling from GIT. If the components exist multiple times its not a problem I have wrapped those with <code>function_exists</code>.</p>
<p>This is what I use in the Theme:</p>
<pre><code>wp_enqueue_script(get_template_directory_uri().'/libs/my_lib/admin_image_upload', ...);
</code></pre>
<p>This is what I use in a Plugin:</p>
<pre><code>wp_enqueue_script(plugins_url(__FILE__).'admin_image_upload.js', ...);
</code></pre>
<p>Is there a way to determine if my current PHP file is within the plugins' folder or within the themes' folder in order that I can let decide for the correct path automatically?</p>
| [
{
"answer_id": 271819,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is there a way to determine if my current PHP file is within the plugins' folder or within the themes' folder</p>\n</blockquote>\n\n<p>Broadly you always have path to current file (<code>__FILE__</code>) so you can always examine it for where you are and compare with context. This might be good enough in custom site, but likely too brittle for public code. There are plenty of edge cases with paths since they can be highly customized.</p>\n\n<p>What you have is not just <em>asset</em> problem, but <em>dependency</em> problem — how do you reuse multiple components, in different ways, and without conflicts.</p>\n\n<p>Personally I’d strongly consider looking into Composer, since it’s de–facto way to manage dependencies in modern PHP. It’s... not perfect for quirks of publicly distributed WP extensions, but your case sounds more like custom–work focused anyway.</p>\n"
},
{
"answer_id": 271825,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a solution that will return the URL to a file relative to its location, as well as string indicating where the file lives, i.e. mu-plugins/plugins/theme.</p>\n\n<p>This code has been adapted from <code>get_url_from_dir()</code> used in the meta box library <a href=\"https://github.com/CMB2/CMB2\" rel=\"nofollow noreferrer\">CMB2</a>.</p>\n\n<pre><code>/**\n * Converts a system file path to a URL.\n * Returns URL and the detected location of the file.\n *\n * Based on get_url_from_dir() via CMB2\n * @link https://github.com/CMB2/CMB2\n * \n * @param string $file file path to convert.\n * @return string Converted URL.\n * @return array|bool (on error)\n * array\n * $url string Converted URL.\n * $location string location of dir (mu-plugins, plugins, theme)\n *\n */\nfunction wpse_get_url_info_from_file( $file ) {\n $file = wp_normalize_path( $file );\n $test_dir = pathinfo( $file );\n\n if ( ! $test_dir ) {\n return false;\n }\n\n $test_dir = trailingslashit( $test_dir['dirname'] );\n\n // Test if we are in the mu-plugins dir.\n if ( 0 === strpos( $test_dir, wp_normalize_path( WPMU_PLUGIN_DIR ) ) ) {\n return [\n 'url' => trailingslashit( plugins_url( '', $file ) ),\n 'location' => 'mu-plugins'\n ];\n }\n\n // Test if we are in the plugins dir.\n if ( 0 === strpos( $test_dir, wp_normalize_path( WP_PLUGIN_DIR ) ) ) {\n return [\n 'url' => trailingslashit( plugins_url( '', $file ) ),\n 'location' => 'plugins'\n ];\n }\n\n // Now let's test if we are in the theme dir.\n $theme_root = wp_normalize_path( get_theme_root() );\n if ( 0 === strpos( $file, $theme_root ) ) {\n // Ok, then use get_theme_root_uri.\n $url = set_url_scheme(\n trailingslashit(\n str_replace(\n untrailingslashit( $theme_root ),\n untrailingslashit( get_theme_root_uri() ),\n $test_dir\n )\n )\n );\n\n return [\n 'url' => $url,\n 'location' => 'theme'\n ];\n }\n}\n</code></pre>\n\n<p>For example, if we have a plugin named <code>wpse</code> living in <code>plugins-directory/wpse</code> and a theme named <code>my-theme</code>, we can use the following code in either the plugin or the theme to enqueue the <code>admin_image_upload.js</code> file, which lives in different directories in the plugin and theme.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_enqueue_js_based_on_location' );\nfunction wpse_enqueue_js_based_on_location() {\n $url_info = wpse_get_url_info_from_file( __FILE__ );\n //exit ( print_r( $url_info ) );\n\n // Bail if something is wrong.\n if ( ! $url_info ) {\n return;\n }\n\n // Bail if something is wrong.\n if ( ! isset( $url_info['url'] ) || ! isset( $url_info['location'] ) ) {\n return;\n }\n\n // Enqueue the JS based on detected location of the file.\n if ( 'plugins' === $url_info['location'] ) {\n wp_enqueue_script( 'wpse-js', plugins_url( '/admin_image_upload.js', __FILE__ ) );\n } elseif ( 'theme' === $url_info['location'] ) {\n wp_enqueue_script( 'wpse-js', get_template_directory_uri() . '/libs/my_lib/admin_image_upload.js' );\n }\n}\n</code></pre>\n\n<p>When using the code above from a file in the root directory of the <code>wpse</code> plugin, <code>$url_info</code> will look like this:</p>\n\n<pre><code>Array(\n [url] => http://example.com/wp-content/plugins/wpse/\n [location] => plugins\n)\n</code></pre>\n\n<p>If we run the same code from within a theme's <code>functions.php</code>, <code>$url_info</code> will look like this:</p>\n\n<pre><code>Array(\n [url] => http://example.com/wp-content/themes/my-theme/\n [location] => theme\n)\n</code></pre>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271814",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
]
| In my projects I have some components which I use in a lot of custom Plugins as well as in some custom coded Themes like e.g. admin image or video selectors.
Those I am holding in custom git repositories. However as those components are used in both - themes and plugins - I always have to manually change the URL getters after pulling from GIT. If the components exist multiple times its not a problem I have wrapped those with `function_exists`.
This is what I use in the Theme:
```
wp_enqueue_script(get_template_directory_uri().'/libs/my_lib/admin_image_upload', ...);
```
This is what I use in a Plugin:
```
wp_enqueue_script(plugins_url(__FILE__).'admin_image_upload.js', ...);
```
Is there a way to determine if my current PHP file is within the plugins' folder or within the themes' folder in order that I can let decide for the correct path automatically? | >
> Is there a way to determine if my current PHP file is within the plugins' folder or within the themes' folder
>
>
>
Broadly you always have path to current file (`__FILE__`) so you can always examine it for where you are and compare with context. This might be good enough in custom site, but likely too brittle for public code. There are plenty of edge cases with paths since they can be highly customized.
What you have is not just *asset* problem, but *dependency* problem — how do you reuse multiple components, in different ways, and without conflicts.
Personally I’d strongly consider looking into Composer, since it’s de–facto way to manage dependencies in modern PHP. It’s... not perfect for quirks of publicly distributed WP extensions, but your case sounds more like custom–work focused anyway. |
271,820 | <p>I have used the Advanced Custom Fields plugin two create two fields, review score and review summary.</p>
<p>I can display these fields on a post no problem, but it displays after everything else like share buttons, author box, pagination, etc.</p>
<p>How can I modify my code so that the custom fields show above everything else, just after the last paragraph of the post?</p>
<p>This is my code to display my custom fields:</p>
<pre><code><?php if( get_field('review_score') ): ?>
<div class="review-score">
<h1>The Last Word</h1>
<div class="score-section">
<span class="review-the-score"><?php the_field('review_score'); ?></span><span class="review-out-of">/10</span>
</div>
<div class="summary-section">
<span class="review-summary"><?php the_field('review_summary'); ?></span></div>
</div>
<?php endif; ?>
Thanks for your help/
</code></pre>
| [
{
"answer_id": 271845,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Plugins typically insert their content via <code>the_content</code> filter. The filter runs when <code>the_content()</code> function is called, and passes the content through the filter before output.</p>\n\n<p>Remember, with a filter, you need to append to the existing content, then <code>return</code> the results.</p>\n\n<pre><code>add_filter( 'the_content', 'wpd_content_filter', 10 );\n\nfunction wpd_content_filter( $content ){\n if ( is_single() && get_field( 'review_score' ) )\n $content .= '<span class=\"review-the-score\">' . get_field( 'review_score' ) . '</span>';\n\n return $content;\n}\n</code></pre>\n\n<p>The third argument of <code>add_filter</code> is the priority (10 in the above example, the default). You may need to make this a lower number if plugin content is appearing above your own.</p>\n"
},
{
"answer_id": 272655,
"author": "Destiny2Gamer",
"author_id": 121998,
"author_profile": "https://wordpress.stackexchange.com/users/121998",
"pm_score": 0,
"selected": false,
"text": "<p>I eventually got this to wrok, I decided to ditch ACF and just work with wordpress custom fields instead, here is my code which now shows the review score and summary above all other plugin stuff, author box etc.</p>\n\n<pre><code> //show review score above other plugin stuff\nadd_filter( 'the_content', 'gwad_review_score', 1);\n\nfunction gwad_review_score( $content ){\n\n global $post;\n\n $revscore = get_post_meta($post->ID, 'review_score', true);\n $revsummary = get_post_meta($post->ID, 'review_summary', true);\n\n if ($revscore) {\n\n $content = $content . '<div class=\"review-score\">' . $revscore . '<p>' . $revsummary . '</p>' . '</div>';\n\n return $content;\n\n }else{\n\n }\n\n}\n</code></pre>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121998/"
]
| I have used the Advanced Custom Fields plugin two create two fields, review score and review summary.
I can display these fields on a post no problem, but it displays after everything else like share buttons, author box, pagination, etc.
How can I modify my code so that the custom fields show above everything else, just after the last paragraph of the post?
This is my code to display my custom fields:
```
<?php if( get_field('review_score') ): ?>
<div class="review-score">
<h1>The Last Word</h1>
<div class="score-section">
<span class="review-the-score"><?php the_field('review_score'); ?></span><span class="review-out-of">/10</span>
</div>
<div class="summary-section">
<span class="review-summary"><?php the_field('review_summary'); ?></span></div>
</div>
<?php endif; ?>
Thanks for your help/
``` | Plugins typically insert their content via `the_content` filter. The filter runs when `the_content()` function is called, and passes the content through the filter before output.
Remember, with a filter, you need to append to the existing content, then `return` the results.
```
add_filter( 'the_content', 'wpd_content_filter', 10 );
function wpd_content_filter( $content ){
if ( is_single() && get_field( 'review_score' ) )
$content .= '<span class="review-the-score">' . get_field( 'review_score' ) . '</span>';
return $content;
}
```
The third argument of `add_filter` is the priority (10 in the above example, the default). You may need to make this a lower number if plugin content is appearing above your own. |
271,826 | <p>I am creating a custom post type and I added the comment option for it. Now all the comments submitted in that post type are also added to the general comment section. </p>
<p>How can I make sure the comment for a specific post type are separated from the general comments in the dashboard area? </p>
| [
{
"answer_id": 271831,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Comments need to belong to a post $id. Check your code to make sure that the comment-saving/processing code is referencing the current post ID.</p>\n"
},
{
"answer_id": 271897,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 2,
"selected": false,
"text": "<p>All comments are just listed under <strong>\"Comments\"</strong> there is no attribute or parameter which creates a seperate <strong>\"Comments\"</strong> section/page for your custom post-type. Atleast not that I know of. </p>\n\n<p><em>However, you could add a filter to the comments list, to filter all comments based on post-types.</em><br>\nIt will be just like a category filter in the post list.</p>\n\n<p>So you can create a <code>HTML select field</code>, which contains an <code>option for every custom post-type</code>. The <code>value</code> of each option needs to be the <code>slug of the post-type</code>. The <code>select</code> element needs <code>a name of \"post_type\"</code> to make the filtering work.</p>\n\n<pre><code>/**\n * Create custom comments filter for post types\n **/\nfunction my_comments_filter() {\n\n // we are only getting the none-default post types here (no post, no page, no attachment)\n // you can also change this, just take a look at the get_post_types() function\n $args = array(\n 'public' => true,\n '_builtin' => false\n );\n $post_types = get_post_types( $args, 'objects' ); // we get the post types as objects\n\n if ($post_types) { // only start if there are custom post types \n\n // make sure the name of the select field is called \"post_type\"\n echo '<select name=\"post_type\" id=\"filter-by-post-type\">';\n\n // I also add an empty option to reset the filtering and show all comments of all post-types\n echo '<option value=\"\">'.__('All post types', 'my-textdomain').'</option>';\n\n // for each post-type that is found, we will create a new <option>\n foreach ($post_types as $post_type) {\n\n $label = $post_type->label; // get the label of the post-type\n $name = $post_type->name; // get the name(slug) of the post-type\n\n // value of the optionsfield is the name(slug) of the post-type\n echo '<option value=\"'.$name.'\">'.$label.'</option>';\n\n }\n echo '</select>';\n } \n\n}\n// we add our action to the 'restrict_manage_comments' hook so that our new select field get listet at the comments page\nadd_action( 'restrict_manage_comments', 'my_comments_filter' );\n</code></pre>\n\n<p>If you add this code to your <code>functions.php</code>, or better, <code>to a plugin</code>, you will see a new filter on the top of the comments backend. Here you can <code>select a custom post-type</code> and than click on <code>Filter</code>, to filter the comments. If you select \"All post types\" and click filter again, all comments should show.</p>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122864/"
]
| I am creating a custom post type and I added the comment option for it. Now all the comments submitted in that post type are also added to the general comment section.
How can I make sure the comment for a specific post type are separated from the general comments in the dashboard area? | All comments are just listed under **"Comments"** there is no attribute or parameter which creates a seperate **"Comments"** section/page for your custom post-type. Atleast not that I know of.
*However, you could add a filter to the comments list, to filter all comments based on post-types.*
It will be just like a category filter in the post list.
So you can create a `HTML select field`, which contains an `option for every custom post-type`. The `value` of each option needs to be the `slug of the post-type`. The `select` element needs `a name of "post_type"` to make the filtering work.
```
/**
* Create custom comments filter for post types
**/
function my_comments_filter() {
// we are only getting the none-default post types here (no post, no page, no attachment)
// you can also change this, just take a look at the get_post_types() function
$args = array(
'public' => true,
'_builtin' => false
);
$post_types = get_post_types( $args, 'objects' ); // we get the post types as objects
if ($post_types) { // only start if there are custom post types
// make sure the name of the select field is called "post_type"
echo '<select name="post_type" id="filter-by-post-type">';
// I also add an empty option to reset the filtering and show all comments of all post-types
echo '<option value="">'.__('All post types', 'my-textdomain').'</option>';
// for each post-type that is found, we will create a new <option>
foreach ($post_types as $post_type) {
$label = $post_type->label; // get the label of the post-type
$name = $post_type->name; // get the name(slug) of the post-type
// value of the optionsfield is the name(slug) of the post-type
echo '<option value="'.$name.'">'.$label.'</option>';
}
echo '</select>';
}
}
// we add our action to the 'restrict_manage_comments' hook so that our new select field get listet at the comments page
add_action( 'restrict_manage_comments', 'my_comments_filter' );
```
If you add this code to your `functions.php`, or better, `to a plugin`, you will see a new filter on the top of the comments backend. Here you can `select a custom post-type` and than click on `Filter`, to filter the comments. If you select "All post types" and click filter again, all comments should show. |
271,832 | <p>I've migrated a site from a live server to a localhost using the WP Migrate DB plugin. I've done this process a couple of times before and it's all been fine. This time however I've migrated a site from an https: connection and I can't get into the site on my localhost. It gives me the following error:</p>
<pre><code>This site can’t provide a secure connection
localhost sent an invalid response.
ERR_SSL_PROTOCOL_ERROR
</code></pre>
<p>I'm guessing that in the back end of Wordpress I need to change something either in the database, or in the Dashboard > Settings > General tab.</p>
<p>At the moment I can't get into the site though, so I would think i'll have to do it via the database?</p>
<p>Any help or assistance would be awesome. I don't quite know where to start.</p>
<p>Paul.</p>
| [
{
"answer_id": 271833,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>In the wp_options table, you will find two rows that have the site URL. Change those two values.</p>\n\n<p>Your media and other links to internal pages might have to adjusted, though. That's why I let the great WP Clone plugin (<a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a> ) do all the work for me. You just install the plugin on the source system, back it up, then install the plugin on the target system, and restore. </p>\n\n<p>Great plugin, takes all the work out of moving (cloning) a site. I sometimes have to do the restore twice (the first fails for a mysterious reason), but the retry works just fine. All data, users, content, etc moved very nicely.</p>\n"
},
{
"answer_id": 271834,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<p>This is because the <code>site_url</code> and <code>homeurl</code> of your original installation are set to HTTPS in the database, so you can't access your website on localhost unless you:</p>\n\n<ol>\n<li>Change these values to non-ssl </li>\n<li>Install a SSL certificate on localhost</li>\n</ol>\n\n<p>I will only explain the first case since installing a certificate is out of this community's scope.</p>\n\n<p>To do this, you have 2 options.</p>\n\n<h2>Directly edit the downloaded SQL file</h2>\n\n<p>Open the MySQL export that you just downloaded from your server. Search for <code>wp_options</code> and you will find a line in your database like this:</p>\n\n<pre><code>INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES\n</code></pre>\n\n<p>The 2 lines below this one are <code>siteurl</code> and <code>homeurl</code>. Change both of their values to <code>http://localhost/</code>. Pay attention to quotes and commas! So, the 3 first line will look like this:</p>\n\n<pre><code>INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES\n(1, 'siteurl', 'http://localhost/', 'yes'),\n(2, 'home', 'http://localhost', 'yes'),\n</code></pre>\n\n<p>Then upload your SQL file. That's it.</p>\n\n<h2>Update the values by PHPMyAdmin</h2>\n\n<p>If you have PHPMyAdmin installed on your localhost, or you have enough knowledge to directly update the tables via command line, the proceed with this method.</p>\n\n<p>Login to your database by PHPMyAdmin. From the left navigation menu, choose the proper database. Now, select the <code>wp_options</code> table from the right section.</p>\n\n<p>Again, the two beginning values will be <code>siteurl</code> and <code>homeurl</code>, which you can simply update to <code>http://localhost/</code> without worrying about making a mistake by editing the original SQL file.</p>\n"
},
{
"answer_id": 303482,
"author": "Gilbert Rodríguez",
"author_id": 143527,
"author_profile": "https://wordpress.stackexchange.com/users/143527",
"pm_score": 0,
"selected": false,
"text": "<p>That you can do quickly with these 2 constants offered by WordPress. </p>\n\n<p>Your add it to the start of the <code>wp-config.php</code> file and after the opening of the <code><?php</code> tags. </p>\n\n<pre><code>define ('WP_HOME', 'http://localhost/wordpress-folder-name' );\ndefine ('WP_SITEURL', 'http://localhost/wordpress-folder-name' );\n</code></pre>\n"
},
{
"answer_id": 355116,
"author": "ZazOufUmI",
"author_id": 180146,
"author_profile": "https://wordpress.stackexchange.com/users/180146",
"pm_score": 1,
"selected": false,
"text": "<p>For my part, it was different from the other answers. My database was set correctly to <code>http://localhost</code> but I had a plugin installed to manage SSL <em>(Really Simple SSL)</em>.</p>\n\n<p>So I renamed the folder <code>/wp-content/plugins/really-simple-ssl</code> to something different and it worked.</p>\n\n<p>And to access <code>/wp-admin</code> without SSL, you need to change your <code>/wp-config.php</code> file and set <code>FORCE_SSL_ADMIN</code> to <code>false</code>.</p>\n"
},
{
"answer_id": 368474,
"author": "Arman H",
"author_id": 134743,
"author_profile": "https://wordpress.stackexchange.com/users/134743",
"pm_score": 1,
"selected": false,
"text": "<p>I have faced this problem. what i did is that- </p>\n\n<ol start=\"2\">\n<li>remove wp-security plugin</li>\n<li>remove wp-config defien force SSL</li>\n<li>removed browser cache</li>\n<li>changed wp-option table site_url and home URL</li>\n<li>updated .htaccess with wp default .htacess</li>\n</ol>\n\n<p>Nothing works.</p>\n\n<p>Finally what I did is that-</p>\n\n<p>Removing <strong>.htaccess permanently works</strong> fine for me.</p>\n\n<p>Hope this will help someone to get rid of this problem.</p>\n"
}
]
| 2017/06/29 | [
"https://wordpress.stackexchange.com/questions/271832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
]
| I've migrated a site from a live server to a localhost using the WP Migrate DB plugin. I've done this process a couple of times before and it's all been fine. This time however I've migrated a site from an https: connection and I can't get into the site on my localhost. It gives me the following error:
```
This site can’t provide a secure connection
localhost sent an invalid response.
ERR_SSL_PROTOCOL_ERROR
```
I'm guessing that in the back end of Wordpress I need to change something either in the database, or in the Dashboard > Settings > General tab.
At the moment I can't get into the site though, so I would think i'll have to do it via the database?
Any help or assistance would be awesome. I don't quite know where to start.
Paul. | This is because the `site_url` and `homeurl` of your original installation are set to HTTPS in the database, so you can't access your website on localhost unless you:
1. Change these values to non-ssl
2. Install a SSL certificate on localhost
I will only explain the first case since installing a certificate is out of this community's scope.
To do this, you have 2 options.
Directly edit the downloaded SQL file
-------------------------------------
Open the MySQL export that you just downloaded from your server. Search for `wp_options` and you will find a line in your database like this:
```
INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
```
The 2 lines below this one are `siteurl` and `homeurl`. Change both of their values to `http://localhost/`. Pay attention to quotes and commas! So, the 3 first line will look like this:
```
INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
(1, 'siteurl', 'http://localhost/', 'yes'),
(2, 'home', 'http://localhost', 'yes'),
```
Then upload your SQL file. That's it.
Update the values by PHPMyAdmin
-------------------------------
If you have PHPMyAdmin installed on your localhost, or you have enough knowledge to directly update the tables via command line, the proceed with this method.
Login to your database by PHPMyAdmin. From the left navigation menu, choose the proper database. Now, select the `wp_options` table from the right section.
Again, the two beginning values will be `siteurl` and `homeurl`, which you can simply update to `http://localhost/` without worrying about making a mistake by editing the original SQL file. |
271,876 | <p>I want to create new post page after every 25 (li /li) tags. Is it possible?</p>
| [
{
"answer_id": 271833,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>In the wp_options table, you will find two rows that have the site URL. Change those two values.</p>\n\n<p>Your media and other links to internal pages might have to adjusted, though. That's why I let the great WP Clone plugin (<a href=\"https://wordpress.org/plugins/wp-clone-by-wp-academy/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-clone-by-wp-academy/</a> ) do all the work for me. You just install the plugin on the source system, back it up, then install the plugin on the target system, and restore. </p>\n\n<p>Great plugin, takes all the work out of moving (cloning) a site. I sometimes have to do the restore twice (the first fails for a mysterious reason), but the retry works just fine. All data, users, content, etc moved very nicely.</p>\n"
},
{
"answer_id": 271834,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<p>This is because the <code>site_url</code> and <code>homeurl</code> of your original installation are set to HTTPS in the database, so you can't access your website on localhost unless you:</p>\n\n<ol>\n<li>Change these values to non-ssl </li>\n<li>Install a SSL certificate on localhost</li>\n</ol>\n\n<p>I will only explain the first case since installing a certificate is out of this community's scope.</p>\n\n<p>To do this, you have 2 options.</p>\n\n<h2>Directly edit the downloaded SQL file</h2>\n\n<p>Open the MySQL export that you just downloaded from your server. Search for <code>wp_options</code> and you will find a line in your database like this:</p>\n\n<pre><code>INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES\n</code></pre>\n\n<p>The 2 lines below this one are <code>siteurl</code> and <code>homeurl</code>. Change both of their values to <code>http://localhost/</code>. Pay attention to quotes and commas! So, the 3 first line will look like this:</p>\n\n<pre><code>INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES\n(1, 'siteurl', 'http://localhost/', 'yes'),\n(2, 'home', 'http://localhost', 'yes'),\n</code></pre>\n\n<p>Then upload your SQL file. That's it.</p>\n\n<h2>Update the values by PHPMyAdmin</h2>\n\n<p>If you have PHPMyAdmin installed on your localhost, or you have enough knowledge to directly update the tables via command line, the proceed with this method.</p>\n\n<p>Login to your database by PHPMyAdmin. From the left navigation menu, choose the proper database. Now, select the <code>wp_options</code> table from the right section.</p>\n\n<p>Again, the two beginning values will be <code>siteurl</code> and <code>homeurl</code>, which you can simply update to <code>http://localhost/</code> without worrying about making a mistake by editing the original SQL file.</p>\n"
},
{
"answer_id": 303482,
"author": "Gilbert Rodríguez",
"author_id": 143527,
"author_profile": "https://wordpress.stackexchange.com/users/143527",
"pm_score": 0,
"selected": false,
"text": "<p>That you can do quickly with these 2 constants offered by WordPress. </p>\n\n<p>Your add it to the start of the <code>wp-config.php</code> file and after the opening of the <code><?php</code> tags. </p>\n\n<pre><code>define ('WP_HOME', 'http://localhost/wordpress-folder-name' );\ndefine ('WP_SITEURL', 'http://localhost/wordpress-folder-name' );\n</code></pre>\n"
},
{
"answer_id": 355116,
"author": "ZazOufUmI",
"author_id": 180146,
"author_profile": "https://wordpress.stackexchange.com/users/180146",
"pm_score": 1,
"selected": false,
"text": "<p>For my part, it was different from the other answers. My database was set correctly to <code>http://localhost</code> but I had a plugin installed to manage SSL <em>(Really Simple SSL)</em>.</p>\n\n<p>So I renamed the folder <code>/wp-content/plugins/really-simple-ssl</code> to something different and it worked.</p>\n\n<p>And to access <code>/wp-admin</code> without SSL, you need to change your <code>/wp-config.php</code> file and set <code>FORCE_SSL_ADMIN</code> to <code>false</code>.</p>\n"
},
{
"answer_id": 368474,
"author": "Arman H",
"author_id": 134743,
"author_profile": "https://wordpress.stackexchange.com/users/134743",
"pm_score": 1,
"selected": false,
"text": "<p>I have faced this problem. what i did is that- </p>\n\n<ol start=\"2\">\n<li>remove wp-security plugin</li>\n<li>remove wp-config defien force SSL</li>\n<li>removed browser cache</li>\n<li>changed wp-option table site_url and home URL</li>\n<li>updated .htaccess with wp default .htacess</li>\n</ol>\n\n<p>Nothing works.</p>\n\n<p>Finally what I did is that-</p>\n\n<p>Removing <strong>.htaccess permanently works</strong> fine for me.</p>\n\n<p>Hope this will help someone to get rid of this problem.</p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122896/"
]
| I want to create new post page after every 25 (li /li) tags. Is it possible? | This is because the `site_url` and `homeurl` of your original installation are set to HTTPS in the database, so you can't access your website on localhost unless you:
1. Change these values to non-ssl
2. Install a SSL certificate on localhost
I will only explain the first case since installing a certificate is out of this community's scope.
To do this, you have 2 options.
Directly edit the downloaded SQL file
-------------------------------------
Open the MySQL export that you just downloaded from your server. Search for `wp_options` and you will find a line in your database like this:
```
INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
```
The 2 lines below this one are `siteurl` and `homeurl`. Change both of their values to `http://localhost/`. Pay attention to quotes and commas! So, the 3 first line will look like this:
```
INSERT INTO `wp_options` (`option_id`, `option_name`, `option_value`, `autoload`) VALUES
(1, 'siteurl', 'http://localhost/', 'yes'),
(2, 'home', 'http://localhost', 'yes'),
```
Then upload your SQL file. That's it.
Update the values by PHPMyAdmin
-------------------------------
If you have PHPMyAdmin installed on your localhost, or you have enough knowledge to directly update the tables via command line, the proceed with this method.
Login to your database by PHPMyAdmin. From the left navigation menu, choose the proper database. Now, select the `wp_options` table from the right section.
Again, the two beginning values will be `siteurl` and `homeurl`, which you can simply update to `http://localhost/` without worrying about making a mistake by editing the original SQL file. |
271,877 | <p>I am trying to filter by a meta query but no matter what I try I can not make it work.</p>
<p>Basically I want this query in through the rest API:</p>
<pre><code>wp-json/wp/v2/books?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==
</code></pre>
<p>Ive tried several different custom fields but it will always return all post objects.</p>
<p>In my functions file I've added:</p>
<pre><code>function api_allow_meta_query( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_query') );
return $valid_vars;
}
add_filter( 'rest_query_vars', 'api_allow_meta_query' );
</code></pre>
<p>I tried finishing some documentation regarding this but couldn't, also most of the similar questions are not for wordpress 4.7 since filter[xxx] is removed.</p>
| [
{
"answer_id": 271887,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 5,
"selected": true,
"text": "<p>You can write your own REST handler for custom queries if you want. In your case, the query can done by doing so:</p>\n\n<pre><code>// Register a REST route\nadd_action( 'rest_api_init', function () {\n //Path to meta query route\n register_rest_route( 'tchernitchenko/v2', '/my_meta_query/', array(\n 'methods' => 'GET', \n 'callback' => 'custom_meta_query' \n ) );\n});\n\n// Do the actual query and return the data\nfunction custom_meta_query(){\n if(isset($_GET['meta_query'])) {\n $query = $_GET['meta_query'];\n // Set the arguments based on our get parameters\n $args = array (\n 'relation' => $query[0]['relation'],\n array(\n 'key' => $query[0]['key'],\n 'value' => $query[0]['value'],\n 'compare' => '=',\n ),\n );\n // Run a custom query\n $meta_query = new WP_Query($args);\n if($meta_query->have_posts()) {\n //Define and empty array\n $data = array();\n // Store each post's title in the array\n while($meta_query->have_posts()) {\n $meta_query->the_post();\n $data[] = get_the_title();\n }\n // Return the data\n return $data;\n } else {\n // If there is no post\n return 'No post to show';\n }\n }\n}\n</code></pre>\n\n<p>Now, all you have to do is to access:</p>\n\n<pre><code>wp-json/tchernitchenko/v2/my_meta_query?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==\n</code></pre>\n"
},
{
"answer_id": 292125,
"author": "Jack Song",
"author_id": 134082,
"author_profile": "https://wordpress.stackexchange.com/users/134082",
"pm_score": 3,
"selected": false,
"text": "<p>The following code should add multiple meta queries capability to all your post types. It supports CPT (Custom Post Type) and ACF (Advanced Custom Field). Source code also available on <a href=\"https://github.com/SK8-PTY-LTD/wp-rest-filter\" rel=\"noreferrer\">Github</a>.</p>\n\n<p>Add it to your function.php</p>\n\n<pre><code>add_action( 'rest_api_init', 'wp_rest_filter_add_filters' );\n /**\n * Add the necessary filter to each post type\n **/\nfunction wp_rest_filter_add_filters() {\n foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {\n add_filter( 'rest_' . $post_type->name . '_query', 'wp_rest_filter_add_filter_param', 10, 2 );\n }\n}\n/**\n * Add the filter parameter\n *\n * @param array $args The query arguments.\n * @param WP_REST_Request $request Full details about the request.\n * @return array $args.\n **/\nfunction wp_rest_filter_add_filter_param( $args, $request ) {\n // Bail out if no filter parameter is set.\n if ( empty( $request['filter'] ) || ! is_array( $request['filter'] ) ) {\n return $args;\n }\n $filter = $request['filter'];\n if ( isset( $filter['posts_per_page'] ) && ( (int) $filter['posts_per_page'] >= 1 && (int) $filter['posts_per_page'] <= 100 ) ) {\n $args['posts_per_page'] = $filter['posts_per_page'];\n }\n global $wp;\n $vars = apply_filters( 'rest_query_vars', $wp->public_query_vars );\n function allow_meta_query( $valid_vars )\n {\n $valid_vars = array_merge( $valid_vars, array( 'meta_query', 'meta_key', 'meta_value', 'meta_compare' ) );\n return $valid_vars;\n }\n $vars = allow_meta_query( $vars );\n\n foreach ( $vars as $var ) {\n if ( isset( $filter[ $var ] ) ) {\n $args[ $var ] = $filter[ $var ];\n }\n }\n return $args;\n}\n</code></pre>\n\n<p>IMHO, a more better way would to include the additional function as a seperate plugin. So even when user changed theme, your api calls won't be affected.</p>\n\n<p>Therefore I've developed a <strong>plugin</strong> for meta query in WordPress. Better yet, it supports ACF too!</p>\n\n<p><a href=\"https://wordpress.org/plugins/wp-rest-filter/\" rel=\"noreferrer\">WP REST Filter</a></p>\n\n<p>After installation, just do a <strong>GET</strong> request in the following format.</p>\n\n<pre><code>https://domain.com/wp-json/acf/v3/customposttype?filter[meta_key]=acfkey&filter[meta_value]=acfvalue\n</code></pre>\n\n<p>Check out the plugin source code from <a href=\"https://github.com/SK8-PTY-LTD/wp-rest-filter\" rel=\"noreferrer\">Github</a>. </p>\n"
},
{
"answer_id": 305337,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 4,
"selected": false,
"text": "<p>Use filter <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"noreferrer\">rest_{CUSTOM_POST_TYPE}_query</a> to add the post meta support in WP Rest API for any post type.</p>\n\n<p>Check the Gist <a href=\"https://gist.github.com/maheshwaghmare/0bbe5eabceed24aa76ef1eabe684a748\" rel=\"noreferrer\">search post by post meta with rest API</a>.</p>\n\n<p><strong>How to use?</strong></p>\n\n<p><code>http://example.org/wp-json/wp/v2/post?meta_key=<my_meta_key>&meta_value=<my_meta_value></code></p>\n\n<p><strong>Example</strong></p>\n\n<p>Get posts which post meta <code>already-visited</code> value is <code>true</code>.</p>\n\n<p><code>http://example.org/wp-json/wp/v2/post?meta_key=already-visited&meta_value=true</code></p>\n\n<p>It ONLY lists the posts which post meta key <code>already-visited</code> have value <code>true</code>.</p>\n\n<p>For reference <a href=\"https://maheshwaghmare.wordpress.com/2018/06/05/search-post-by-post-meta-with-rest-api/\" rel=\"noreferrer\">Search post by post meta with rest api</a>.</p>\n\n<p><strong>Available Filters</strong></p>\n\n<ul>\n<li>rest_post_query</li>\n<li>rest_page_query</li>\n<li>rest_attachment_query</li>\n</ul>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93224/"
]
| I am trying to filter by a meta query but no matter what I try I can not make it work.
Basically I want this query in through the rest API:
```
wp-json/wp/v2/books?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==
```
Ive tried several different custom fields but it will always return all post objects.
In my functions file I've added:
```
function api_allow_meta_query( $valid_vars ) {
$valid_vars = array_merge( $valid_vars, array( 'meta_query') );
return $valid_vars;
}
add_filter( 'rest_query_vars', 'api_allow_meta_query' );
```
I tried finishing some documentation regarding this but couldn't, also most of the similar questions are not for wordpress 4.7 since filter[xxx] is removed. | You can write your own REST handler for custom queries if you want. In your case, the query can done by doing so:
```
// Register a REST route
add_action( 'rest_api_init', function () {
//Path to meta query route
register_rest_route( 'tchernitchenko/v2', '/my_meta_query/', array(
'methods' => 'GET',
'callback' => 'custom_meta_query'
) );
});
// Do the actual query and return the data
function custom_meta_query(){
if(isset($_GET['meta_query'])) {
$query = $_GET['meta_query'];
// Set the arguments based on our get parameters
$args = array (
'relation' => $query[0]['relation'],
array(
'key' => $query[0]['key'],
'value' => $query[0]['value'],
'compare' => '=',
),
);
// Run a custom query
$meta_query = new WP_Query($args);
if($meta_query->have_posts()) {
//Define and empty array
$data = array();
// Store each post's title in the array
while($meta_query->have_posts()) {
$meta_query->the_post();
$data[] = get_the_title();
}
// Return the data
return $data;
} else {
// If there is no post
return 'No post to show';
}
}
}
```
Now, all you have to do is to access:
```
wp-json/tchernitchenko/v2/my_meta_query?meta_query[relation]=OR&meta_query[0][key]=arkivera&meta_query[0][value]=1&meta_query[0][compare]==
``` |
271,878 | <p>I am used to creating websites outside of wordpress just using HTML, CSS and JS. Normally if I want to create a link to a page, about-us.html, I simply add:</p>
<pre><code><a href="/about-us.html">About Us</a>
</code></pre>
<p>I have an HTML based template which I converted to wordpress theme via FTP. If I want to accomplish the same thing am I just supposed to reference about-us.php like:</p>
<pre><code><a href="/about-us.php">About Us</a>
</code></pre>
<p>Where about-us.php is:</p>
<pre><code><?php
/**
* Template Name: About Us
*
* @package WordPress
* @subpackage Besa
* @since Besa HTML5 3.0
*/
get_header(); ?>
<?php include('/about.html');?>
<?php get_footer(); ?>
</code></pre>
<p>Is this all that is needed? Should I be copy and pasting the HTML instead of using the include statement? Do I have to create a new page in the wordpress editor? Do I have to select a PAge Attribute Template, and if so why?</p>
<p>Thanks!</p>
<p>EDIT: When I try my method I just get an error "Fatal error: Call to undefined function get_header() in /home/besa/public_html/about-us.php on line 10"</p>
| [
{
"answer_id": 271881,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually <em>exist</em> anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.</p>\n\n<p>In your case, you should create a file name <code>about-us.php</code> instead of <code>about-us.html</code> and then include it in your template by using this:</p>\n\n<pre><code>get_template_part('path/to/this/file/about-us.php');\n</code></pre>\n\n<p>Now you will be able to create a page from admin panel and use this file as its template.</p>\n\n<p>As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.</p>\n\n<p>To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:</p>\n\n<pre><code><?php echo site_url('/some-path/slug-goes-here'); ?>\n</code></pre>\n\n<p>The above function with append <code>/some-path/slug-goes-here</code> to your site's URL and output it, which would be your page's link.</p>\n"
},
{
"answer_id": 271961,
"author": "WpDeal.net",
"author_id": 122940,
"author_profile": "https://wordpress.stackexchange.com/users/122940",
"pm_score": -1,
"selected": false,
"text": "<p>try</p>\n\n<pre><code><?php echo get_bloginfo('url').'/about.html'; ?>\n</code></pre>\n"
},
{
"answer_id": 387434,
"author": "Dushan",
"author_id": 140188,
"author_profile": "https://wordpress.stackexchange.com/users/140188",
"pm_score": 0,
"selected": false,
"text": "<p>First, create a page from WordPress Admin called "<strong>About Us</strong>". Then choose the page template from the right sidebar of the "About Us" page under "<strong>Page Attributes</strong>" section. Then use the following code in any of your template files where you want to create a link to "About Us" page.</p>\n<pre><code><?php echo get_site_url(); ?>/about-us\n</code></pre>\n<p><strong>Note that "about-us" is the page slug</strong></p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122624/"
]
| I am used to creating websites outside of wordpress just using HTML, CSS and JS. Normally if I want to create a link to a page, about-us.html, I simply add:
```
<a href="/about-us.html">About Us</a>
```
I have an HTML based template which I converted to wordpress theme via FTP. If I want to accomplish the same thing am I just supposed to reference about-us.php like:
```
<a href="/about-us.php">About Us</a>
```
Where about-us.php is:
```
<?php
/**
* Template Name: About Us
*
* @package WordPress
* @subpackage Besa
* @since Besa HTML5 3.0
*/
get_header(); ?>
<?php include('/about.html');?>
<?php get_footer(); ?>
```
Is this all that is needed? Should I be copy and pasting the HTML instead of using the include statement? Do I have to create a new page in the wordpress editor? Do I have to select a PAge Attribute Template, and if so why?
Thanks!
EDIT: When I try my method I just get an error "Fatal error: Call to undefined function get\_header() in /home/besa/public\_html/about-us.php on line 10" | WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually *exist* anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.
In your case, you should create a file name `about-us.php` instead of `about-us.html` and then include it in your template by using this:
```
get_template_part('path/to/this/file/about-us.php');
```
Now you will be able to create a page from admin panel and use this file as its template.
As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.
To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:
```
<?php echo site_url('/some-path/slug-goes-here'); ?>
```
The above function with append `/some-path/slug-goes-here` to your site's URL and output it, which would be your page's link. |
271,879 | <p>So this is what I'm fruitlessly trying to achieve - let's say there's a menu like the following...</p>
<p><a href="https://i.stack.imgur.com/yIbO2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIbO2.png" alt="enter image description here"></a></p>
<p>What I'd like to do is to generate a menu with just the title and the link of the current page the user is on and it's immediate children. For example let's say the user is currently on Sample Page - the menu should look like this...</p>
<p><a href="https://i.stack.imgur.com/FTgBk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTgBk.png" alt="enter image description here"></a></p>
<p>If the user is currently viewing the Woo page, the generated menu should contain a link to the Woo page and it's children (Shop, Cart, Checkout, My Account). If the page the user is viewing has no children like on Yet Another Page, it should only display a link to the page the user is currently on (Yet Another Page in this case).</p>
<p>Is something like this possible to achieve? If so, how can I do this? Any tips would be greatly appreciated and thank you in advance.</p>
| [
{
"answer_id": 271881,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually <em>exist</em> anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.</p>\n\n<p>In your case, you should create a file name <code>about-us.php</code> instead of <code>about-us.html</code> and then include it in your template by using this:</p>\n\n<pre><code>get_template_part('path/to/this/file/about-us.php');\n</code></pre>\n\n<p>Now you will be able to create a page from admin panel and use this file as its template.</p>\n\n<p>As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.</p>\n\n<p>To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:</p>\n\n<pre><code><?php echo site_url('/some-path/slug-goes-here'); ?>\n</code></pre>\n\n<p>The above function with append <code>/some-path/slug-goes-here</code> to your site's URL and output it, which would be your page's link.</p>\n"
},
{
"answer_id": 271961,
"author": "WpDeal.net",
"author_id": 122940,
"author_profile": "https://wordpress.stackexchange.com/users/122940",
"pm_score": -1,
"selected": false,
"text": "<p>try</p>\n\n<pre><code><?php echo get_bloginfo('url').'/about.html'; ?>\n</code></pre>\n"
},
{
"answer_id": 387434,
"author": "Dushan",
"author_id": 140188,
"author_profile": "https://wordpress.stackexchange.com/users/140188",
"pm_score": 0,
"selected": false,
"text": "<p>First, create a page from WordPress Admin called "<strong>About Us</strong>". Then choose the page template from the right sidebar of the "About Us" page under "<strong>Page Attributes</strong>" section. Then use the following code in any of your template files where you want to create a link to "About Us" page.</p>\n<pre><code><?php echo get_site_url(); ?>/about-us\n</code></pre>\n<p><strong>Note that "about-us" is the page slug</strong></p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122407/"
]
| So this is what I'm fruitlessly trying to achieve - let's say there's a menu like the following...
[](https://i.stack.imgur.com/yIbO2.png)
What I'd like to do is to generate a menu with just the title and the link of the current page the user is on and it's immediate children. For example let's say the user is currently on Sample Page - the menu should look like this...
[](https://i.stack.imgur.com/FTgBk.png)
If the user is currently viewing the Woo page, the generated menu should contain a link to the Woo page and it's children (Shop, Cart, Checkout, My Account). If the page the user is viewing has no children like on Yet Another Page, it should only display a link to the page the user is currently on (Yet Another Page in this case).
Is something like this possible to achieve? If so, how can I do this? Any tips would be greatly appreciated and thank you in advance. | WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually *exist* anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.
In your case, you should create a file name `about-us.php` instead of `about-us.html` and then include it in your template by using this:
```
get_template_part('path/to/this/file/about-us.php');
```
Now you will be able to create a page from admin panel and use this file as its template.
As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.
To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:
```
<?php echo site_url('/some-path/slug-goes-here'); ?>
```
The above function with append `/some-path/slug-goes-here` to your site's URL and output it, which would be your page's link. |
271,893 | <p>When I do something like:</p>
<pre><code>$prevPost = get_previous_post();
</code></pre>
<p>I can then do:</p>
<pre><code>$prevPost->post_title;
$prevPost->post_content;
...
</code></pre>
<p>Why can't I get the permalink?</p>
<pre><code>$prevPost->post_url; // NULL
$prevPost->post_permalink; // NULL
</code></pre>
<p>Obviously, as stated in the <a href="https://codex.wordpress.org/Class_Reference/WP_Post" rel="nofollow noreferrer">codex</a>, that class doesn't have these properties. However, it seems logical to have the post URL as part of <em>the post</em>. Why is that not the case?</p>
<p>To get the permalink, I need to do:</p>
<pre><code>get_permalink($prevPost);
</code></pre>
<p>But then, I can't do something like this to get the title:</p>
<pre><code>get_title($prevPost);
</code></pre>
<hr>
<h2>Questions</h2>
<ol>
<li><p>What's the reason for these inconsistencies? Why do I have to get some of the post data via the post object and other - with the <code>get</code> functions? I'm relatively new to WordPress, so an article explaining it all would be much appreciated.</p></li>
<li><p>Are there any other types of data that share these inconsistencies? What are they?</p></li>
</ol>
| [
{
"answer_id": 271881,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually <em>exist</em> anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.</p>\n\n<p>In your case, you should create a file name <code>about-us.php</code> instead of <code>about-us.html</code> and then include it in your template by using this:</p>\n\n<pre><code>get_template_part('path/to/this/file/about-us.php');\n</code></pre>\n\n<p>Now you will be able to create a page from admin panel and use this file as its template.</p>\n\n<p>As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.</p>\n\n<p>To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:</p>\n\n<pre><code><?php echo site_url('/some-path/slug-goes-here'); ?>\n</code></pre>\n\n<p>The above function with append <code>/some-path/slug-goes-here</code> to your site's URL and output it, which would be your page's link.</p>\n"
},
{
"answer_id": 271961,
"author": "WpDeal.net",
"author_id": 122940,
"author_profile": "https://wordpress.stackexchange.com/users/122940",
"pm_score": -1,
"selected": false,
"text": "<p>try</p>\n\n<pre><code><?php echo get_bloginfo('url').'/about.html'; ?>\n</code></pre>\n"
},
{
"answer_id": 387434,
"author": "Dushan",
"author_id": 140188,
"author_profile": "https://wordpress.stackexchange.com/users/140188",
"pm_score": 0,
"selected": false,
"text": "<p>First, create a page from WordPress Admin called "<strong>About Us</strong>". Then choose the page template from the right sidebar of the "About Us" page under "<strong>Page Attributes</strong>" section. Then use the following code in any of your template files where you want to create a link to "About Us" page.</p>\n<pre><code><?php echo get_site_url(); ?>/about-us\n</code></pre>\n<p><strong>Note that "about-us" is the page slug</strong></p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122905/"
]
| When I do something like:
```
$prevPost = get_previous_post();
```
I can then do:
```
$prevPost->post_title;
$prevPost->post_content;
...
```
Why can't I get the permalink?
```
$prevPost->post_url; // NULL
$prevPost->post_permalink; // NULL
```
Obviously, as stated in the [codex](https://codex.wordpress.org/Class_Reference/WP_Post), that class doesn't have these properties. However, it seems logical to have the post URL as part of *the post*. Why is that not the case?
To get the permalink, I need to do:
```
get_permalink($prevPost);
```
But then, I can't do something like this to get the title:
```
get_title($prevPost);
```
---
Questions
---------
1. What's the reason for these inconsistencies? Why do I have to get some of the post data via the post object and other - with the `get` functions? I'm relatively new to WordPress, so an article explaining it all would be much appreciated.
2. Are there any other types of data that share these inconsistencies? What are they? | WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually *exist* anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.
In your case, you should create a file name `about-us.php` instead of `about-us.html` and then include it in your template by using this:
```
get_template_part('path/to/this/file/about-us.php');
```
Now you will be able to create a page from admin panel and use this file as its template.
As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.
To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:
```
<?php echo site_url('/some-path/slug-goes-here'); ?>
```
The above function with append `/some-path/slug-goes-here` to your site's URL and output it, which would be your page's link. |
271,927 | <p>I'm wondering what the best practice is for storing images, css, js etc in my file manager. I've come up with these 2 possible options as my preferred options.</p>
<ol>
<li>Create folders (<code>images/</code>, <code>css/</code>, <code>js/</code>) in the root directory</li>
</ol>
<p>And refer to these files like <code><img src="/images/image1.png"></code> for example...</p>
<p>OR</p>
<ol start="2">
<li>Create folders (<code>images/</code>, <code>css/</code>, <code>js/</code>) in the specific theme directory</li>
</ol>
<p>And refer to these files like <code><img src="<?php bloginfo('template_directory'); ?>/images/image1.png"></code> for example...</p>
<p>I'm wondering if there is a standard or a preferred practice? I'm new to wordpress and php and would like to start off doing things correctly now, rather than trying to fix problems in the future.</p>
<p>Thanks!</p>
| [
{
"answer_id": 271881,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually <em>exist</em> anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.</p>\n\n<p>In your case, you should create a file name <code>about-us.php</code> instead of <code>about-us.html</code> and then include it in your template by using this:</p>\n\n<pre><code>get_template_part('path/to/this/file/about-us.php');\n</code></pre>\n\n<p>Now you will be able to create a page from admin panel and use this file as its template.</p>\n\n<p>As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.</p>\n\n<p>To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:</p>\n\n<pre><code><?php echo site_url('/some-path/slug-goes-here'); ?>\n</code></pre>\n\n<p>The above function with append <code>/some-path/slug-goes-here</code> to your site's URL and output it, which would be your page's link.</p>\n"
},
{
"answer_id": 271961,
"author": "WpDeal.net",
"author_id": 122940,
"author_profile": "https://wordpress.stackexchange.com/users/122940",
"pm_score": -1,
"selected": false,
"text": "<p>try</p>\n\n<pre><code><?php echo get_bloginfo('url').'/about.html'; ?>\n</code></pre>\n"
},
{
"answer_id": 387434,
"author": "Dushan",
"author_id": 140188,
"author_profile": "https://wordpress.stackexchange.com/users/140188",
"pm_score": 0,
"selected": false,
"text": "<p>First, create a page from WordPress Admin called "<strong>About Us</strong>". Then choose the page template from the right sidebar of the "About Us" page under "<strong>Page Attributes</strong>" section. Then use the following code in any of your template files where you want to create a link to "About Us" page.</p>\n<pre><code><?php echo get_site_url(); ?>/about-us\n</code></pre>\n<p><strong>Note that "about-us" is the page slug</strong></p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271927",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122624/"
]
| I'm wondering what the best practice is for storing images, css, js etc in my file manager. I've come up with these 2 possible options as my preferred options.
1. Create folders (`images/`, `css/`, `js/`) in the root directory
And refer to these files like `<img src="/images/image1.png">` for example...
OR
2. Create folders (`images/`, `css/`, `js/`) in the specific theme directory
And refer to these files like `<img src="<?php bloginfo('template_directory'); ?>/images/image1.png">` for example...
I'm wondering if there is a standard or a preferred practice? I'm new to wordpress and php and would like to start off doing things correctly now, rather than trying to fix problems in the future.
Thanks! | WordPress doesn't work that way. In WordPress, none of the posts or pages that you visit actually *exist* anywhere on the disk. The content is grabbed from database and then the template files are filled with them and sent to browser.
In your case, you should create a file name `about-us.php` instead of `about-us.html` and then include it in your template by using this:
```
get_template_part('path/to/this/file/about-us.php');
```
Now you will be able to create a page from admin panel and use this file as its template.
As for your questions about link... Again you shouldn't directly link to a PHP file, because it simply won't work. If you access a PHP file directly, it doesn't load WordPress's engine when it is loading.
To do so, you should use the slug. Create a page, write down its slug, and then create a dynamic link in your PHP template like this:
```
<?php echo site_url('/some-path/slug-goes-here'); ?>
```
The above function with append `/some-path/slug-goes-here` to your site's URL and output it, which would be your page's link. |
271,934 | <p>So, I'm totally new to WordPress and trying to "convert" a static site to a WP theme.</p>
<p>I have a page where I'd like to use the featured image as a background for a div.</p>
<p>I was wondering what is the best way or whats the convention to do that? </p>
<p>It doesn't matter if its a featured image or whatever, I just want the user to be able to change the image from the dashboard.</p>
<p>I'd shy away from inlining if possible, so is that the only option?</p>
| [
{
"answer_id": 271941,
"author": "samjco",
"author_id": 29133,
"author_profile": "https://wordpress.stackexchange.com/users/29133",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Here is an example of in-page styling. :)</strong> </p>\n\n<pre><code><?php get_header(); \n\n\n <div id=\"primary\" class=\"content-area\">\n <main id=\"main\" class=\"site-main\" role=\"main\">\n\n <?php\n // Start the loop.\n while ( have_posts() ) : the_post();\n\n if ( has_post_thumbnail( $_post->ID ) ) { ?>\n\n <style>\n .featureimg{\n /* dynamic img url */\n background: url(<?= get_the_post_thumbnail( $_post->ID,'large' );?>);\n\n /* full width */\n width:100%;\n\n /* half height */\n height: 50%; \n\n /* Center and scale the image nicely */\n background-position: center;\n background-repeat: no-repeat;\n background-size: cover;\n }\n </style>\n\n <div class=\"featureimg\"></div>\n <div class=\"title\"><?php the_title();?></div>\n <div class=\"content\"><?php the_content();?></div>\n\n\n <?php \n // If comments are open or we have at least one comment, load up the comment template.\n if ( comments_open() || get_comments_number() ) :\n comments_template();\n endif;\n\n // End the loop.\n endwhile;\n ?>\n\n </main><!-- .site-main -->\n </div><!-- .content-area -->\n\n <?php get_footer(); ?>\n</code></pre>\n"
},
{
"answer_id": 271944,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 1,
"selected": false,
"text": "<p>There's two possible options in creating a stylesheet from a dynamically generated value. The first options is <strong>Inline stylesheet</strong>, as follows:</p>\n\n<pre><code><div id=\"hero\" \n style=\"background-image: url(<?php // TODO retrieve image here. ?>); \">\n</div>\n</code></pre>\n\n<p>And the second options is to use an <strong>Internal stylesheet</strong>, and possibly the best solution out of both. Using stylesheet internally requires you to have your <code>div</code> an identifier possibly assigning the <em>ID</em>, or <em>class</em>, code as follows:</p>\n\n<pre><code><div id=\"hero\"></div>\n</code></pre>\n\n<p>The <strong>Internal stylesheet</strong>:</p>\n\n<pre><code><style>\n #hero {\n background-image: url('<?php // TODO retrieve image here. ?>');\n background-position: 50% 50%;\n background-size: cover;\n }\n</style>\n</code></pre>\n\n<p>Using <strong>External stylesheet</strong> to retrieve and assign the value of the image from the database is impossible. You can still use external stylesheet for the rest of the styles of your <code>div</code>; i.e. <code>#hero</code>, and have the image be retrieve and assign via inline/internal stylesheet.</p>\n"
},
{
"answer_id": 271971,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Obviously, since you want a different background image for every page, you cannot include the css in a static file. You will have to generate it on the fly.</p>\n\n<p>The easiest way would be to include the css between <code><style></code> tags in your template files. The other answers show you how to do this.</p>\n\n<p>The most 'WordPressy' way would be different, namely to handle this in your <code>functions.php</code> file as virtual stylesheet using <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_style/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_style</code></a>. Essentially this means you are adding some statements to an already existing css file. Your styling will end up in the head of the page, where it belongs, in stead of the body (which works, but is semantically incorrect).</p>\n\n<p>So, in your functions file you would have, for instance:</p>\n\n<pre><code>add_action ('wp_enqueue_style','wpse271934_add_styles');\nfunction wpse271934_add_styles () {\n global $post;\n $extra_styling = '';\n if (is_page() || is_single ()) {\n $image = get_the_post_thumbnail ($post->ID,'large');\n if (!empty($image))\n $extra_styling = '.post, .page {background:url(' . $image . ');}';\n }\n // assuming style.css has the handle 'main_style' in your theme\n wp_add_inline_style ('main_style', $extra_styling);\n }\n</code></pre>\n\n<p>In the above example (which I didn't test, so watch for bugs) we are adding the background image to single pages and posts. But you have more possibilities. For instance <a href=\"https://codex.wordpress.org/Function_Reference/is_404\" rel=\"nofollow noreferrer\">testing for 404</a> pages and defining a background image for that, insert a certain background if there is none, do different things for different category pages and so on. So, apart from being the most correct approach this also gives you most possibilities to control your backgrounds.</p>\n"
}
]
| 2017/06/30 | [
"https://wordpress.stackexchange.com/questions/271934",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70511/"
]
| So, I'm totally new to WordPress and trying to "convert" a static site to a WP theme.
I have a page where I'd like to use the featured image as a background for a div.
I was wondering what is the best way or whats the convention to do that?
It doesn't matter if its a featured image or whatever, I just want the user to be able to change the image from the dashboard.
I'd shy away from inlining if possible, so is that the only option? | There's two possible options in creating a stylesheet from a dynamically generated value. The first options is **Inline stylesheet**, as follows:
```
<div id="hero"
style="background-image: url(<?php // TODO retrieve image here. ?>); ">
</div>
```
And the second options is to use an **Internal stylesheet**, and possibly the best solution out of both. Using stylesheet internally requires you to have your `div` an identifier possibly assigning the *ID*, or *class*, code as follows:
```
<div id="hero"></div>
```
The **Internal stylesheet**:
```
<style>
#hero {
background-image: url('<?php // TODO retrieve image here. ?>');
background-position: 50% 50%;
background-size: cover;
}
</style>
```
Using **External stylesheet** to retrieve and assign the value of the image from the database is impossible. You can still use external stylesheet for the rest of the styles of your `div`; i.e. `#hero`, and have the image be retrieve and assign via inline/internal stylesheet. |
271,964 | <p>After a user registers using WooCommerce's registration form, I want to redirect them to a custom page, such as my other website, instead of the <code>my-account</code> page. </p>
<pre><code>add_action('woocommerce_registration_redirect', 'ps_wc_registration_redirect',10);
function ps_wc_registration_redirect( $redirect_to ) {
$redirect_to ="http://example.com";
return $redirect_to;
}
</code></pre>
<p>The hook above successfully redirects users when the destination is a page on the current site, but when the redirect location is off of the current site, it does not work.</p>
<p>Is there any other hook available after the user registration redirection occurs?</p>
| [
{
"answer_id": 271985,
"author": "Regolith",
"author_id": 103884,
"author_profile": "https://wordpress.stackexchange.com/users/103884",
"pm_score": 0,
"selected": false,
"text": "<p>try setting the function as below, also there is no need of parameter to the function if you are manually setting the link in the function</p>\n\n<pre><code>function custom_registration_redirect_after_registration() {\n return home_url('/post_slug_or_page_slug');\n}\nadd_action('woocommerce_registration_redirect', 'custom_registration_redirect_after_registration', 2);\n</code></pre>\n"
},
{
"answer_id": 272077,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>Internally, WooCommerce uses WordPress' <code>wp_safe_redirect()</code> which does not allow redirects to external hosts. In order to get around this, we must add our desired host to the whitelist. The whitelist can be modified using the <code>allowed_redirect_hosts</code> which has been demonstrated below:</p>\n\n<pre><code>/**\n * Adds example.com to the list of allowed hosts when redirecting using wp_safe_redirect()\n *\n * @param array $hosts An array of allowed hosts.\n * @param bool|string $host The parsed host; empty if not isset.\n */\nadd_filter( 'allowed_redirect_hosts', 'wpse_allowed_redirect_hosts', 10, 2 );\nfunction wpse_allowed_redirect_hosts( $hosts, $host ) {\n $hosts[] = 'example.com';\n\n return $hosts;\n}\n</code></pre>\n\n<p>Use the code above along with your original code (customizing the host as needed) to allow WooCommerce users to be redirected to an external domain after completing the registration process.</p>\n"
}
]
| 2017/07/01 | [
"https://wordpress.stackexchange.com/questions/271964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122941/"
]
| After a user registers using WooCommerce's registration form, I want to redirect them to a custom page, such as my other website, instead of the `my-account` page.
```
add_action('woocommerce_registration_redirect', 'ps_wc_registration_redirect',10);
function ps_wc_registration_redirect( $redirect_to ) {
$redirect_to ="http://example.com";
return $redirect_to;
}
```
The hook above successfully redirects users when the destination is a page on the current site, but when the redirect location is off of the current site, it does not work.
Is there any other hook available after the user registration redirection occurs? | Internally, WooCommerce uses WordPress' `wp_safe_redirect()` which does not allow redirects to external hosts. In order to get around this, we must add our desired host to the whitelist. The whitelist can be modified using the `allowed_redirect_hosts` which has been demonstrated below:
```
/**
* Adds example.com to the list of allowed hosts when redirecting using wp_safe_redirect()
*
* @param array $hosts An array of allowed hosts.
* @param bool|string $host The parsed host; empty if not isset.
*/
add_filter( 'allowed_redirect_hosts', 'wpse_allowed_redirect_hosts', 10, 2 );
function wpse_allowed_redirect_hosts( $hosts, $host ) {
$hosts[] = 'example.com';
return $hosts;
}
```
Use the code above along with your original code (customizing the host as needed) to allow WooCommerce users to be redirected to an external domain after completing the registration process. |
271,968 | <p>I have been struggling with an archive template for a custom post type. I want to display the posts grouped alphabetically by a custom taxonomy called countryname. I tried more than half a dozen examples and finally found one that almost works.</p>
<p>Here is my code so far. When I get this working I will pull in the postmeta, but for now I'd be happy just getting the titles under the correct country.</p>
<p>What I want will look something like this</p>
<pre><code>Canada
- a post
- another post
England
- this post
United States
- short post
- some post
- that post
</code></pre>
<p>But right now it looks like this:</p>
<pre><code>Canada
- a post
- a post
England
- a post
United States
- a post
- a post
- a post
</code></pre>
<p>I added wp_reset_postdata() But that didn't work either. Can someone help me troubleshoot this? It seems that the problem must be in the query to return each custom post within this taxonomy category.</p>
<p>Thank you!</p>
<pre><code>$taxonomy = array( "name" => 'countryname' , "slug" => 'countryname');
$custom_post_type = "tours";
if ( have_posts() )
the_post();
?>
<?php
// Query your specified taxonomy to get, in order, each category
$categories = get_terms($taxonomy['name'], 'orderby=title');
foreach( $categories as $category ) {
?>
<div id="content">
<h2 class="page-title">
<?php echo $category->name; ?>
</h2>
<?php
// Setup query to return each custom post within this taxonomy category
$o_queried_posts = get_posts(array(
'nopaging' => true,
'post_type' => $custom_post_type,
'taxonomy' => $category->taxonomy,
'term' => $category->slug,
));
?>
<div id='archive-content'>
<?php
// Loop through each custom post type
foreach($o_queried_posts as $o_post) {
?>
<div id="post-<?php the_ID(); ?>">
<h2 class="entry-title"><?php the_title(); ?></h2>
</div><!-- #post -->
<?php wp_reset_postdata();
} // foreach($o_queried_posts as $o_post)
?>
</div> <!-- archive-content -->
</div> <!-- #content -->
<?php } // foreach( $categories as $category )
</code></pre>
| [
{
"answer_id": 271976,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 3,
"selected": true,
"text": "<p>You're almost there. Since <code>the_title</code> inside your custom loop is one of the <em>Post template tags</em> you need to assign the global <code>$post</code> to use the new data from the custom query.</p>\n\n<pre><code><?php\n global $post; // Access the global $post object.\n\n // Setup query to return each custom post within this taxonomy category\n $o_queried_posts = get_posts(array(\n 'nopaging' => true,\n 'post_type' => $custom_post_type,\n 'taxonomy' => $category->taxonomy,\n 'term' => $category->slug,\n ));\n?>\n\n<div id='archive-content'>\n\n<?php\n// Loop through each custom post type\nforeach($o_queried_posts as $post) : \n setup_postdata($post); // setup post data to use the Post template tags. ?>\n\n <div id=\"post-<?php the_ID(); ?>\">\n\n <h2 class=\"entry-title\"><?php the_title(); ?></h2>\n\n\n </div><!-- #post -->\n<?php endforeach; wp_reset_postdata(); ?>\n\n</div> <!-- archive-content -->\n</code></pre>\n"
},
{
"answer_id": 271982,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><?php \n $taxonomy = array( \"name\" => 'countryname' , \"slug\" => 'countryname');\n $custom_post_type = \"tours\";\n\n if ( have_posts() ):\n\n // Query your specified taxonomy to get, in order, each category\n $categories = get_terms($taxonomy['name'], 'orderby=title');\n foreach( $categories as $category ):\n ?>\n\n <div id=\"content\"> \n <h2 class=\"page-title\">\n <?php echo $category->name; ?>\n </h2>\n\n <?php\n // Setup query to return each custom post within this taxonomy category\n $args = array(\n 'post_type' = $custom_post_type,\n 'tax_query' => array(\n array(\n 'taxonomy' => $taxonomy[\"name\"],\n 'terms' => $category->slug;\n )\n ) \n );\n\n $query = new WP_Query( $args );\n ?>\n\n <div id='archive-content'>\n\n <?php\n while( $query->have_posts() ): $query->the_post();\n ?>\n\n <div id=\"post-<?php the_ID(); ?>\">\n\n <h2 class=\"entry-title\"><?php the_title(); ?></h2>\n\n\n </div><!-- #post -->\n <?php\n endwhile(); \n wp_reset_postdata();\n ?>\n </div> <!-- archive-content -->\n </div> <!-- #content -->\n <?php endforeach; // foreach( $categories as $category )\n endif;?> \n</code></pre>\n"
}
]
| 2017/07/01 | [
"https://wordpress.stackexchange.com/questions/271968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36252/"
]
| I have been struggling with an archive template for a custom post type. I want to display the posts grouped alphabetically by a custom taxonomy called countryname. I tried more than half a dozen examples and finally found one that almost works.
Here is my code so far. When I get this working I will pull in the postmeta, but for now I'd be happy just getting the titles under the correct country.
What I want will look something like this
```
Canada
- a post
- another post
England
- this post
United States
- short post
- some post
- that post
```
But right now it looks like this:
```
Canada
- a post
- a post
England
- a post
United States
- a post
- a post
- a post
```
I added wp\_reset\_postdata() But that didn't work either. Can someone help me troubleshoot this? It seems that the problem must be in the query to return each custom post within this taxonomy category.
Thank you!
```
$taxonomy = array( "name" => 'countryname' , "slug" => 'countryname');
$custom_post_type = "tours";
if ( have_posts() )
the_post();
?>
<?php
// Query your specified taxonomy to get, in order, each category
$categories = get_terms($taxonomy['name'], 'orderby=title');
foreach( $categories as $category ) {
?>
<div id="content">
<h2 class="page-title">
<?php echo $category->name; ?>
</h2>
<?php
// Setup query to return each custom post within this taxonomy category
$o_queried_posts = get_posts(array(
'nopaging' => true,
'post_type' => $custom_post_type,
'taxonomy' => $category->taxonomy,
'term' => $category->slug,
));
?>
<div id='archive-content'>
<?php
// Loop through each custom post type
foreach($o_queried_posts as $o_post) {
?>
<div id="post-<?php the_ID(); ?>">
<h2 class="entry-title"><?php the_title(); ?></h2>
</div><!-- #post -->
<?php wp_reset_postdata();
} // foreach($o_queried_posts as $o_post)
?>
</div> <!-- archive-content -->
</div> <!-- #content -->
<?php } // foreach( $categories as $category )
``` | You're almost there. Since `the_title` inside your custom loop is one of the *Post template tags* you need to assign the global `$post` to use the new data from the custom query.
```
<?php
global $post; // Access the global $post object.
// Setup query to return each custom post within this taxonomy category
$o_queried_posts = get_posts(array(
'nopaging' => true,
'post_type' => $custom_post_type,
'taxonomy' => $category->taxonomy,
'term' => $category->slug,
));
?>
<div id='archive-content'>
<?php
// Loop through each custom post type
foreach($o_queried_posts as $post) :
setup_postdata($post); // setup post data to use the Post template tags. ?>
<div id="post-<?php the_ID(); ?>">
<h2 class="entry-title"><?php the_title(); ?></h2>
</div><!-- #post -->
<?php endforeach; wp_reset_postdata(); ?>
</div> <!-- archive-content -->
``` |
271,987 | <p>I have a problem with this request with <code>get_posts</code>,when I want to order by title with year, order by doesn't work but when I do it without year, the request works. </p>
<pre><code> $args = array(
'post_type' => 'projects',
'posts_per_page' => -1,
'year' => date( 'Y' )-2,
'orderby'=> 'title',
'order' => 'ASC',);
$myposts = get_posts( $args );
</code></pre>
| [
{
"answer_id": 271996,
"author": "Cesar Henrique Damascena",
"author_id": 109804,
"author_profile": "https://wordpress.stackexchange.com/users/109804",
"pm_score": 1,
"selected": true,
"text": "<p>I tried your code and is working fine for me</p>\n\n<pre><code>$args = array( 'post_type' => 'project','posts_per_page' => -1,'year' => date('Y') - 2, 'orderby'=> 'title','order' => 'ASC');\n\n$myposts = get_posts( $args );\n</code></pre>\n\n<p>The thing is as you can see he is only fetching the posts from 2015. If you don't have any posts with the <strong>publish date from 2015</strong> you will get nothing, but if you want to grab all posts <strong>from two years ago until the current year</strong> you have to do the following:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'project',\n 'posts_per_page' => -1,\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'date_query' => array(\n array(\n 'after' => date('Y')-2 . ' year ago'\n )\n ),\n);\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">WP_Query</a> for reference</p>\n"
},
{
"answer_id": 272015,
"author": "Laurent Jaedong",
"author_id": 122961,
"author_profile": "https://wordpress.stackexchange.com/users/122961",
"pm_score": 1,
"selected": false,
"text": "<p>with date_query i can use successfully this code : </p>\n\n<pre><code>$args = array(\n 'post_type' => 'projects',\n 'posts_per_page' => -1,\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'date_query' => array(\n array(\n 'after' => date('Y')-2\n )\n ),\n); \n</code></pre>\n\n<p>but \"after\" is a little different\nor this code do the same that my first request : </p>\n\n<pre><code> $args = array(\n 'post_type' => 'projects',\n 'posts_per_page' => -1,\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'date_query' => array(\n array(\n 'year' => date('Y')-2\n )\n ),\n); \n</code></pre>\n"
}
]
| 2017/07/01 | [
"https://wordpress.stackexchange.com/questions/271987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122961/"
]
| I have a problem with this request with `get_posts`,when I want to order by title with year, order by doesn't work but when I do it without year, the request works.
```
$args = array(
'post_type' => 'projects',
'posts_per_page' => -1,
'year' => date( 'Y' )-2,
'orderby'=> 'title',
'order' => 'ASC',);
$myposts = get_posts( $args );
``` | I tried your code and is working fine for me
```
$args = array( 'post_type' => 'project','posts_per_page' => -1,'year' => date('Y') - 2, 'orderby'=> 'title','order' => 'ASC');
$myposts = get_posts( $args );
```
The thing is as you can see he is only fetching the posts from 2015. If you don't have any posts with the **publish date from 2015** you will get nothing, but if you want to grab all posts **from two years ago until the current year** you have to do the following:
```
$args = array(
'post_type' => 'project',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'date_query' => array(
array(
'after' => date('Y')-2 . ' year ago'
)
),
);
```
See [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters) for reference |
271,997 | <p>I want to run a <strong>function A()</strong> when a post is published and <strong>function B()</strong> when the same post is edited or updated. </p>
<p>For this, I found <em>publish_post</em> action which is triggered whenever a post is published, or if it is edited and the status is changed to publish.</p>
<p>How can I use this <em>publish_post</em> action to know that post has been edited or updated so that I can run <strong>function B()</strong>?</p>
| [
{
"answer_id": 272001,
"author": "BenB",
"author_id": 62909,
"author_profile": "https://wordpress.stackexchange.com/users/62909",
"pm_score": 1,
"selected": false,
"text": "<p>You could achieve this with save_post hook.</p>\n\n<p>Example similar to code in <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\">codex</a></p>\n\n<pre><code>function run_my_function( $post_id ) {\n if ( wp_is_post_revision( $post_id ) ){\n // if post udpated\n } else {\n //if is new post\n }\n}\nadd_action( 'save_post', 'run_my_function' );\n</code></pre>\n"
},
{
"answer_id": 272002,
"author": "Cesar Henrique Damascena",
"author_id": 109804,
"author_profile": "https://wordpress.stackexchange.com/users/109804",
"pm_score": 2,
"selected": false,
"text": "<p>With the <code>post_updated</code> hook you can trigger an action when the post is updated. He passes 3 parameters: </p>\n\n<ul>\n<li><code>$post_ID</code> (the post ID),</li>\n<li><code>$post_after</code>(the post object after the edit),</li>\n<li><code>$post_before</code> (the post object before the edit)</li>\n</ul>\n\n<p>Here's an example:</p>\n\n<pre><code><?php\nfunction check_values($post_ID, $post_after, $post_before){\n echo 'Post ID:';\n var_dump($post_ID);\n\n echo 'Post Object AFTER update:';\n var_dump($post_after);\n\n echo 'Post Object BEFORE update:';\n var_dump($post_before);\n}\n\nadd_action( 'post_updated', 'check_values', 10, 3 ); //don't forget the last argument to allow all three arguments of the function\n?>\n</code></pre>\n\n<p>See reference <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated\" rel=\"nofollow noreferrer\">Codex</a></p>\n"
}
]
| 2017/07/01 | [
"https://wordpress.stackexchange.com/questions/271997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23717/"
]
| I want to run a **function A()** when a post is published and **function B()** when the same post is edited or updated.
For this, I found *publish\_post* action which is triggered whenever a post is published, or if it is edited and the status is changed to publish.
How can I use this *publish\_post* action to know that post has been edited or updated so that I can run **function B()**? | With the `post_updated` hook you can trigger an action when the post is updated. He passes 3 parameters:
* `$post_ID` (the post ID),
* `$post_after`(the post object after the edit),
* `$post_before` (the post object before the edit)
Here's an example:
```
<?php
function check_values($post_ID, $post_after, $post_before){
echo 'Post ID:';
var_dump($post_ID);
echo 'Post Object AFTER update:';
var_dump($post_after);
echo 'Post Object BEFORE update:';
var_dump($post_before);
}
add_action( 'post_updated', 'check_values', 10, 3 ); //don't forget the last argument to allow all three arguments of the function
?>
```
See reference [Codex](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.