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"
}... | 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>W... | 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 lov... | 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()... | 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 ... | 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 ... | 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 ... | 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 ... | 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 ... | 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 ... | 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... | 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... | 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_Referen... | 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_Referen... | 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_Referen... | 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 count... | 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 ... | 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 ... | 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_w... | 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/\" re... | 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... | 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... | 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<... | 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<... | 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... | 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 a... | 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... | 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-re... | 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', '... | 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... | 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... | 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/f... | 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_i... | 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_i... | 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 ar... | 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 ar... | 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... | 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... | 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 = "you@yourdomail.com";
$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("my@mail.com", "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 lik... | 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 = "you@yourdomail.com";
$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("my@mail.com", "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 lik... | 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 ... | 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 ‘_crosssel... | 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.... | 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.... | 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... | 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 ... | 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 mean... | 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 mor... | 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 th... | 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 li... | 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><... | 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</co... | 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 a... | 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... | 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 m... | 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 m... | 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/\" re... | 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 li... | 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 looki... | 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\">poly... | 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 y... | 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 f... | 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... | 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/\" r... | 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/\" r... | 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... | 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 ... | 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 ... | 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 WordPres... | 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_revi... | 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_ico... | 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 ... | 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 ... | 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-boo... | 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>woocommerc... | 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/refere... | 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 ... | 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 p... | 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 p... | 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> ... | 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 thi... | 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 thi... | 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 thi... | 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 thi... | 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 sit... | 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 them... | 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... | 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... | 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... | 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... | 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 doin... | 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<... | 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<... | 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<... | 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<... | 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(); ... | 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 ... | 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... | 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' =... | 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.wordpre... | 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) |