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
|
---|---|---|---|---|---|---|
256,669 | <p>I am registering the stylesheet and scripts but It is not working please help me. What I am doing wrong </p>
<pre><code>function theme_styles_and_scripts() {
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
</code></pre>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are adding the CSS file in a child theme. In that case, use the following CODE instead:</p>\n\n<pre><code> function theme_styles_and_scripts() {\n wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a> returns the URL of your current theme (whether it is a child theme or not). On the other hand, <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.</p>\n\n<p><strong>Possibility-2:</strong> You are not calling <code>wp_head()</code> anywhere in your theme's template files (usually <code>header.php</code>). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.</p>\n\n<p><strong>Other Possibilities:</strong></p>\n\n<p>However, if you view HTML source & see that you are finding <code>bootstrap</code> in it, then perhaps another call to <code>wp_enqueue_style</code> with the same name is overriding it (<a href=\"https://wordpress.stackexchange.com/a/256674/110572\">as suggested by this answer</a>) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.</p>\n\n<p><strong>How to Debug:</strong></p>\n\n<p>An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:</p>\n\n<pre><code> body {\n background-color: red !important;\n }\n</code></pre>\n\n<p>Then save the CSS file in your theme's <code>css</code> folder with the name <code>wpse256672-style.css</code>.</p>\n\n<p>Then use the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code> function wpse256672_css_enqueue() {\n wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );\n</code></pre>\n\n<p>Now if you reload the page after saving the above, you should see red background in your page. That means you don't have <code>Possibility-2</code> above, but perhaps <code>Possibility-1</code> or something else. Change CSS file name, <code>$handle</code> from <code>bootstrap</code> to something else, change version number, check if the file exists etc.</p>\n\n<blockquote>\n <p>Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.</p>\n</blockquote>\n"
},
{
"answer_id": 256674,
"author": "50bbx",
"author_id": 64670,
"author_profile": "https://wordpress.stackexchange.com/users/64670",
"pm_score": 0,
"selected": false,
"text": "<p>There is a third possibility, because, as <code>wp_enqueue_style</code> documentation says, the <code>$handle</code>param must be unique as it will not override an existing handle.\nYou should try and change the <code>$handle</code> param to something more specific.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108146/"
]
| I am registering the stylesheet and scripts but It is not working please help me. What I am doing wrong
```
function theme_styles_and_scripts() {
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
``` | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,682 | <p>I want to display dates in <strong>Hindi</strong> format like</p>
<pre><code>jan 10
</code></pre>
<p>using <code>get_the_date()</code> function. What I have tried so far:</p>
<pre><code>echo get_the_date(_e('F j'));
</code></pre>
<p>which outputs:</p>
<pre><code>F jJanuary 10, 2017.
</code></pre>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are adding the CSS file in a child theme. In that case, use the following CODE instead:</p>\n\n<pre><code> function theme_styles_and_scripts() {\n wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a> returns the URL of your current theme (whether it is a child theme or not). On the other hand, <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.</p>\n\n<p><strong>Possibility-2:</strong> You are not calling <code>wp_head()</code> anywhere in your theme's template files (usually <code>header.php</code>). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.</p>\n\n<p><strong>Other Possibilities:</strong></p>\n\n<p>However, if you view HTML source & see that you are finding <code>bootstrap</code> in it, then perhaps another call to <code>wp_enqueue_style</code> with the same name is overriding it (<a href=\"https://wordpress.stackexchange.com/a/256674/110572\">as suggested by this answer</a>) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.</p>\n\n<p><strong>How to Debug:</strong></p>\n\n<p>An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:</p>\n\n<pre><code> body {\n background-color: red !important;\n }\n</code></pre>\n\n<p>Then save the CSS file in your theme's <code>css</code> folder with the name <code>wpse256672-style.css</code>.</p>\n\n<p>Then use the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code> function wpse256672_css_enqueue() {\n wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );\n</code></pre>\n\n<p>Now if you reload the page after saving the above, you should see red background in your page. That means you don't have <code>Possibility-2</code> above, but perhaps <code>Possibility-1</code> or something else. Change CSS file name, <code>$handle</code> from <code>bootstrap</code> to something else, change version number, check if the file exists etc.</p>\n\n<blockquote>\n <p>Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.</p>\n</blockquote>\n"
},
{
"answer_id": 256674,
"author": "50bbx",
"author_id": 64670,
"author_profile": "https://wordpress.stackexchange.com/users/64670",
"pm_score": 0,
"selected": false,
"text": "<p>There is a third possibility, because, as <code>wp_enqueue_style</code> documentation says, the <code>$handle</code>param must be unique as it will not override an existing handle.\nYou should try and change the <code>$handle</code> param to something more specific.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112924/"
]
| I want to display dates in **Hindi** format like
```
jan 10
```
using `get_the_date()` function. What I have tried so far:
```
echo get_the_date(_e('F j'));
```
which outputs:
```
F jJanuary 10, 2017.
``` | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,702 | <p>How can I query only those pages that <strong>DO NOT HAVE</strong> child pages?</p>
<p>E.g.:</p>
<ul>
<li>Parent page 1
<ul>
<li>Child page 1</li>
<li>Child page 2</li>
</ul></li>
<li>Parent page 2</li>
<li>Parent page 3
<ul>
<li>Child page 1</li>
<li>Child page 2</li>
</ul></li>
<li>Parent page 4</li>
</ul>
<p>I would like to show </p>
<ul>
<li>Parent page 2</li>
<li>Parent page 4</li>
</ul>
<p><pre><code>
$newQuery = new WP_Query( array (
'posts_per_page' => -1,
'post_type' => 'page',
// Solution?
) );
</pre></code> </p>
<p>Thanks</p>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are adding the CSS file in a child theme. In that case, use the following CODE instead:</p>\n\n<pre><code> function theme_styles_and_scripts() {\n wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a> returns the URL of your current theme (whether it is a child theme or not). On the other hand, <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.</p>\n\n<p><strong>Possibility-2:</strong> You are not calling <code>wp_head()</code> anywhere in your theme's template files (usually <code>header.php</code>). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.</p>\n\n<p><strong>Other Possibilities:</strong></p>\n\n<p>However, if you view HTML source & see that you are finding <code>bootstrap</code> in it, then perhaps another call to <code>wp_enqueue_style</code> with the same name is overriding it (<a href=\"https://wordpress.stackexchange.com/a/256674/110572\">as suggested by this answer</a>) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.</p>\n\n<p><strong>How to Debug:</strong></p>\n\n<p>An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:</p>\n\n<pre><code> body {\n background-color: red !important;\n }\n</code></pre>\n\n<p>Then save the CSS file in your theme's <code>css</code> folder with the name <code>wpse256672-style.css</code>.</p>\n\n<p>Then use the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code> function wpse256672_css_enqueue() {\n wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );\n</code></pre>\n\n<p>Now if you reload the page after saving the above, you should see red background in your page. That means you don't have <code>Possibility-2</code> above, but perhaps <code>Possibility-1</code> or something else. Change CSS file name, <code>$handle</code> from <code>bootstrap</code> to something else, change version number, check if the file exists etc.</p>\n\n<blockquote>\n <p>Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.</p>\n</blockquote>\n"
},
{
"answer_id": 256674,
"author": "50bbx",
"author_id": 64670,
"author_profile": "https://wordpress.stackexchange.com/users/64670",
"pm_score": 0,
"selected": false,
"text": "<p>There is a third possibility, because, as <code>wp_enqueue_style</code> documentation says, the <code>$handle</code>param must be unique as it will not override an existing handle.\nYou should try and change the <code>$handle</code> param to something more specific.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33745/"
]
| How can I query only those pages that **DO NOT HAVE** child pages?
E.g.:
* Parent page 1
+ Child page 1
+ Child page 2
* Parent page 2
* Parent page 3
+ Child page 1
+ Child page 2
* Parent page 4
I would like to show
* Parent page 2
* Parent page 4
```
$newQuery = new WP_Query( array (
'posts_per_page' => -1,
'post_type' => 'page',
// Solution?
) );
```
Thanks | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,705 | <p>I am new for wordpress and i am using Ubuntu OS on my computer I want to run a downloded theme on localhost how can i do that?</p>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are adding the CSS file in a child theme. In that case, use the following CODE instead:</p>\n\n<pre><code> function theme_styles_and_scripts() {\n wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a> returns the URL of your current theme (whether it is a child theme or not). On the other hand, <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a> returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.</p>\n\n<p><strong>Possibility-2:</strong> You are not calling <code>wp_head()</code> anywhere in your theme's template files (usually <code>header.php</code>). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.</p>\n\n<p><strong>Other Possibilities:</strong></p>\n\n<p>However, if you view HTML source & see that you are finding <code>bootstrap</code> in it, then perhaps another call to <code>wp_enqueue_style</code> with the same name is overriding it (<a href=\"https://wordpress.stackexchange.com/a/256674/110572\">as suggested by this answer</a>) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.</p>\n\n<p><strong>How to Debug:</strong></p>\n\n<p>An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:</p>\n\n<pre><code> body {\n background-color: red !important;\n }\n</code></pre>\n\n<p>Then save the CSS file in your theme's <code>css</code> folder with the name <code>wpse256672-style.css</code>.</p>\n\n<p>Then use the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code> function wpse256672_css_enqueue() {\n wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );\n }\n add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );\n</code></pre>\n\n<p>Now if you reload the page after saving the above, you should see red background in your page. That means you don't have <code>Possibility-2</code> above, but perhaps <code>Possibility-1</code> or something else. Change CSS file name, <code>$handle</code> from <code>bootstrap</code> to something else, change version number, check if the file exists etc.</p>\n\n<blockquote>\n <p>Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.</p>\n</blockquote>\n"
},
{
"answer_id": 256674,
"author": "50bbx",
"author_id": 64670,
"author_profile": "https://wordpress.stackexchange.com/users/64670",
"pm_score": 0,
"selected": false,
"text": "<p>There is a third possibility, because, as <code>wp_enqueue_style</code> documentation says, the <code>$handle</code>param must be unique as it will not override an existing handle.\nYou should try and change the <code>$handle</code> param to something more specific.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113280/"
]
| I am new for wordpress and i am using Ubuntu OS on my computer I want to run a downloded theme on localhost how can i do that? | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,707 | <p>I'm displaying a gallery image but I also want display the caption for image. I can get the info that we insert when us upload a image in WordPress Dashboard like "Title/Caption/ALT/Description". I want get anyone and display.</p>
<pre><code><?php
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) :
?>
<div class="item" style="background-image: url('<?php echo $image_url ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_url->"DESCRIPTION/TITLE/ALT"; ?> </h2>
</div>
</div>
</code></pre>
<p>Reading at the docs of <a href="https://codex.wordpress.org/Function_Reference/get_post_gallery_images" rel="nofollow noreferrer">get_post_gallery_images</a> I didn't find a solution for my issue. <br>
I also found <a href="https://wordpress.stackexchange.com/questions/125554/get-image-description">this answer</a> but I don't know if it works and I've erros to implement in my code.</p>
<p>Anyway, how can I solve this?</p>
| [
{
"answer_id": 256715,
"author": "Kyon147",
"author_id": 102156,
"author_profile": "https://wordpress.stackexchange.com/users/102156",
"pm_score": 2,
"selected": false,
"text": "<p>The caption for an image is actually meta_data attached to the image and the <a href=\"https://developer.wordpress.org/reference/functions/get_post_gallery_images/\" rel=\"nofollow noreferrer\">get_post_gallery_images only returns a url</a>, so in the array you won't have any other information.</p>\n\n<p>You could try something like:</p>\n\n<pre><code><?php \n $gallery = get_post_gallery_images( $post );\n foreach( $gallery as $image_url ) : \n\n //get the id of the image post.\n $image_id = url_to_postid( $image_url ) \n //get the image \"post\" information\n $image = get_post($image_id);\n //get the image title\n $image_title = $image->post_title;\n //get the image caption\n $image_caption = $image->post_excerpt;\n\n?> \n\n <div class=\"item\" style=\"background-image: url('<?php echo $image_url ?>'); background-size: cover\">\n <div class=\"caption\"> \n <!-- Here I want display the Title/Caption/ALT/Description of image -->\n <h2><?php echo $image_caption; ?> </h2>\n </div> \n </div>\n</code></pre>\n"
},
{
"answer_id": 256719,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>You need to get the <code>metadata</code> of each image, add this to your <code>functions.php</code> file:</p>\n\n<pre><code>function get_post_gallery_images_with_info($postvar = NULL) {\n if(!isset($postvar)){\n global $post;\n $postvar = $post;//if the param wasnt sent\n }\n\n\n $post_content = $postvar->post_content;\n preg_match('/\\[gallery.*ids=.(.*).\\]/', $post_content, $ids);\n $images_id = explode(\",\", $ids[1]); //we get the list of IDs of the gallery as an Array\n\n\n $image_gallery_with_info = array();\n //we get the info for each ID\n foreach ($images_id as $image_id) {\n $attachment = get_post($image_id);\n array_push($image_gallery_with_info, array(\n 'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),\n 'caption' => $attachment->post_excerpt,\n 'description' => $attachment->post_content,\n 'href' => get_permalink($attachment->ID),\n 'src' => $attachment->guid,\n 'title' => $attachment->post_title\n )\n );\n }\n return $image_gallery_with_info;\n}\n</code></pre>\n\n<p>use it in your logic like this:</p>\n\n<pre><code><?php \n $gallery = get_post_gallery_images_with_info($post); //you can use it without params too\n foreach( $gallery as $image_obj ) : \n?> \n\n <div class=\"item\" style=\"background-image: url('<?php echo $image_obj['src'] ?>'); background-size: cover\">\n <div class=\"caption\"> \n <!-- Here I want display the Title/Caption/ALT/Description of image -->\n <h2><?php echo $image_obj['title'].\" \". $image_obj['caption'].\" \".$image_obj['description']; ?> </h2>\n </div> \n </div>\n<?php \nendforeach;\n?>\n</code></pre>\n\n<p>it will output like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/2sZ2N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2sZ2N.png\" alt=\"enter image description here\"></a></p>\n\n<p>each image returned by the function is an array like this:</p>\n\n<pre><code>Array\n (\n [alt] => Alt Coffe\n [caption] => Caption coffe\n [description] => Description coffe\n [href] => http://yoursite/2017/02/14/hello-world/coffee/\n [src] => http://yoursite/wp-content/uploads/sites/4/2017/02/coffee.jpg\n [title] => coffee\n )\n</code></pre>\n\n<p>notice <code>href</code> and <code>src</code> are different, one is the permalink and the other the direct <code>URL</code>.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94215/"
]
| I'm displaying a gallery image but I also want display the caption for image. I can get the info that we insert when us upload a image in WordPress Dashboard like "Title/Caption/ALT/Description". I want get anyone and display.
```
<?php
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) :
?>
<div class="item" style="background-image: url('<?php echo $image_url ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_url->"DESCRIPTION/TITLE/ALT"; ?> </h2>
</div>
</div>
```
Reading at the docs of [get\_post\_gallery\_images](https://codex.wordpress.org/Function_Reference/get_post_gallery_images) I didn't find a solution for my issue.
I also found [this answer](https://wordpress.stackexchange.com/questions/125554/get-image-description) but I don't know if it works and I've erros to implement in my code.
Anyway, how can I solve this? | You need to get the `metadata` of each image, add this to your `functions.php` file:
```
function get_post_gallery_images_with_info($postvar = NULL) {
if(!isset($postvar)){
global $post;
$postvar = $post;//if the param wasnt sent
}
$post_content = $postvar->post_content;
preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
$images_id = explode(",", $ids[1]); //we get the list of IDs of the gallery as an Array
$image_gallery_with_info = array();
//we get the info for each ID
foreach ($images_id as $image_id) {
$attachment = get_post($image_id);
array_push($image_gallery_with_info, array(
'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink($attachment->ID),
'src' => $attachment->guid,
'title' => $attachment->post_title
)
);
}
return $image_gallery_with_info;
}
```
use it in your logic like this:
```
<?php
$gallery = get_post_gallery_images_with_info($post); //you can use it without params too
foreach( $gallery as $image_obj ) :
?>
<div class="item" style="background-image: url('<?php echo $image_obj['src'] ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_obj['title']." ". $image_obj['caption']." ".$image_obj['description']; ?> </h2>
</div>
</div>
<?php
endforeach;
?>
```
it will output like this:
[](https://i.stack.imgur.com/2sZ2N.png)
each image returned by the function is an array like this:
```
Array
(
[alt] => Alt Coffe
[caption] => Caption coffe
[description] => Description coffe
[href] => http://yoursite/2017/02/14/hello-world/coffee/
[src] => http://yoursite/wp-content/uploads/sites/4/2017/02/coffee.jpg
[title] => coffee
)
```
notice `href` and `src` are different, one is the permalink and the other the direct `URL`. |
256,717 | <p>I'm trying to change the logo url of the site to "mywebsite.com/side2", but it is not working, can anyone tell me where is the error in the code below?</p>
<pre><code>add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
return home_url( 'side2' );
}
</code></pre>
| [
{
"answer_id": 256718,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the <strong>get_page_by_path</strong> as follows:</p>\n\n<pre><code>add_filter( 'login_headerurl', 'custom_loginlogo_url' );\nfunction custom_loginlogo_url($url) {\n\n return get_page_by_path( 'side2' );\n}\n</code></pre>\n"
},
{
"answer_id": 256723,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>login_headerurl</code> filter is for changing the logo url of login page, according to the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl\" rel=\"nofollow noreferrer\">Codex</a>. </p>\n\n<p>To change the logo URL of your homepage, you will have to look into your theme's <code>header.php</code> file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.</p>\n\n<p>Access your <code>header.php</code> file from <code>Appearance > Edit</code> in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want.</p>\n"
},
{
"answer_id": 256737,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>If the theme author is using <code>bloginfo('url')</code> to output the url, then you can do the following. </p>\n\n<p><code>bloginfo('url')</code> is a wrapper for <code>echo get_bloginfo('url')</code> which is a wrapper for <code>home_url()</code> which in turn is a wrapper for <code>get_home_url()</code>. The code for that function is available <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/link-template.php#L2989\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>As can be seen, there is a filter available at the end of the function that you can use to change the value of the home url.</p>\n\n<p>Edited so that the filters only fire for the home_url and custom_logo filters are both called.</p>\n\n<pre><code>add_filter( 'home_url', 'wpse_106269_home_url', 10, 4 );\nfunction wpse_106269_home_url( $url, $path, $orig_scheme, $blog_id ) {\n add_filter( 'custom_logo', 'wpse_106269_custom_logo', 10, 2 );\n}\n\nfunction wpse_106269_custom_logo( $html, $blog_id ) {\n //* Remove the filter\n remove_filter( 'custom_logo', 'wpse_106269_custom_logo', 10, 2 );\n\n //* Use str_replace() to change link\n return str_replace( $old_url, $new_url, $html );\n}\n</code></pre>\n"
},
{
"answer_id": 278350,
"author": "Rakesh Solanki",
"author_id": 126723,
"author_profile": "https://wordpress.stackexchange.com/users/126723",
"pm_score": 2,
"selected": false,
"text": "<p>You can Use this function to change the Logo url in Wordpress.</p>\n\n<h2>Simple add this code in function.php file</h2>\n\n<pre><code>//changing the url on the logo to redirect them\nfunction mb_login_url() { return home_url(); }\nadd_filter( 'login_headerurl', 'mb_login_url' );\n\n// changing the alt text on the logo to show your site name\nfunction mb_login_title() { return get_option( 'blogname' ); }\nadd_filter( 'login_headertitle', 'mb_login_title' );\n</code></pre>\n\n<hr>\n\n<h2>To change the Logo in Admin side login page</h2>\n\n<pre><code>function my_login_logo_one() { \n?> \n<style type=\"text/css\"> \nbody.login div#login h1 a {\nbackground-image: url(http://sitetitle.com/logo-1.png); \n}\n</style>\n<?php }\nadd_action( 'login_enqueue_scripts', 'my_login_logo_one' );\n</code></pre>\n"
},
{
"answer_id": 363359,
"author": "Niels Lange",
"author_id": 112118,
"author_profile": "https://wordpress.stackexchange.com/users/112118",
"pm_score": 1,
"selected": false,
"text": "<p>In case anyone else if facing the same issue, I created the plugin <a href=\"https://wordpress.org/plugins/smntcs-custom-logo-link/\" rel=\"nofollow noreferrer\">SMNTCS Custom Logo Link</a> a while ago, which works with all themes that have 100.000+ active installations. If the theme that you're using is not among those themes, simply create an issue on <a href=\"https://github.com/nielslange/smntcs-custom-logo-link/issues\" rel=\"nofollow noreferrer\">https://github.com/nielslange/smntcs-custom-logo-link/issues</a> and I'm happy to extend the plugin. </p>\n"
},
{
"answer_id": 368422,
"author": "Voltaki",
"author_id": 132144,
"author_profile": "https://wordpress.stackexchange.com/users/132144",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to add this jQuery code</p>\n\n<pre><code>jQuery(document).ready(function($){ \n $(\"a.logo-class\").attr(\"href\", \"https://google.com\");\n});\n</code></pre>\n"
},
{
"answer_id": 393707,
"author": "Adrian Laurenzi",
"author_id": 210612,
"author_profile": "https://wordpress.stackexchange.com/users/210612",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up taking the following Javascript-based approach which worked for my purposes. I am using the theme from <a href=\"https://theme.co/x\" rel=\"nofollow noreferrer\">https://theme.co/x</a>. I installed the Insert Headers and Footers plugin and then added the following Javascript (Footer section):</p>\n<pre><code><script>\n document.getElementsByClassName('x-brand')[0].setAttribute("href", "https://example.com");\n</script>\n</code></pre>\n<p>You will need to change the <code>'x-brand'</code> to point to the class of the logo href element specific for the given theme you are using.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256717",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113413/"
]
| I'm trying to change the logo url of the site to "mywebsite.com/side2", but it is not working, can anyone tell me where is the error in the code below?
```
add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
return home_url( 'side2' );
}
``` | The `login_headerurl` filter is for changing the logo url of login page, according to the [Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl).
To change the logo URL of your homepage, you will have to look into your theme's `header.php` file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.
Access your `header.php` file from `Appearance > Edit` in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want. |
256,724 | <p>I'm using a child theme based on 'Twenty Seventeen' and have created a custom post type ('review').</p>
<p>I want to make two Pages, one which lists 'reviews' and the other which lists a mixture of 'posts' and 'reviews' (ordered by recency).</p>
<p>For the first of those I've made a copy of Twenty Seventeen's <code>index.php</code>, as <code>page-reviews.php</code>, and added code like this at the start:</p>
<pre><code>$args = array(
'post_type' => 'review',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 10,
);
$the_query = new WP_Query( $args );
</code></pre>
<p>Then, further down, replaced <code>have_posts()</code> and <code>the_post()</code> with <code>$the_query->have_posts()</code> and <code>$the_query->the_post()</code> respectively.</p>
<p>If I choose to use that template for a Page then it works in that the 'reviews' are listed, <em>but</em> the layout is all messed up. There are a lot of classes in the <code><body></code> which mess up the layout.</p>
<p>For example, the standard blog front page, using <code>index.php</code>, has these classes in its <code><body></code> and looks fine:</p>
<pre><code>blog logged-in admin-bar hfeed has-header-image has-sidebar colors-light customize-support
</code></pre>
<p>While my custom page has these:</p>
<pre><code>page-template page-template-page-postslist page-template-page-postslist-php page page-id-15071 logged-in admin-bar has-header-image page-two-column colors-light customize-support
</code></pre>
<p>How can I make a custom template that acts more like <code>index.php</code> in terms of the classes it adds?</p>
| [
{
"answer_id": 256718,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the <strong>get_page_by_path</strong> as follows:</p>\n\n<pre><code>add_filter( 'login_headerurl', 'custom_loginlogo_url' );\nfunction custom_loginlogo_url($url) {\n\n return get_page_by_path( 'side2' );\n}\n</code></pre>\n"
},
{
"answer_id": 256723,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>login_headerurl</code> filter is for changing the logo url of login page, according to the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl\" rel=\"nofollow noreferrer\">Codex</a>. </p>\n\n<p>To change the logo URL of your homepage, you will have to look into your theme's <code>header.php</code> file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.</p>\n\n<p>Access your <code>header.php</code> file from <code>Appearance > Edit</code> in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want.</p>\n"
},
{
"answer_id": 256737,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>If the theme author is using <code>bloginfo('url')</code> to output the url, then you can do the following. </p>\n\n<p><code>bloginfo('url')</code> is a wrapper for <code>echo get_bloginfo('url')</code> which is a wrapper for <code>home_url()</code> which in turn is a wrapper for <code>get_home_url()</code>. The code for that function is available <a href=\"https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/link-template.php#L2989\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>As can be seen, there is a filter available at the end of the function that you can use to change the value of the home url.</p>\n\n<p>Edited so that the filters only fire for the home_url and custom_logo filters are both called.</p>\n\n<pre><code>add_filter( 'home_url', 'wpse_106269_home_url', 10, 4 );\nfunction wpse_106269_home_url( $url, $path, $orig_scheme, $blog_id ) {\n add_filter( 'custom_logo', 'wpse_106269_custom_logo', 10, 2 );\n}\n\nfunction wpse_106269_custom_logo( $html, $blog_id ) {\n //* Remove the filter\n remove_filter( 'custom_logo', 'wpse_106269_custom_logo', 10, 2 );\n\n //* Use str_replace() to change link\n return str_replace( $old_url, $new_url, $html );\n}\n</code></pre>\n"
},
{
"answer_id": 278350,
"author": "Rakesh Solanki",
"author_id": 126723,
"author_profile": "https://wordpress.stackexchange.com/users/126723",
"pm_score": 2,
"selected": false,
"text": "<p>You can Use this function to change the Logo url in Wordpress.</p>\n\n<h2>Simple add this code in function.php file</h2>\n\n<pre><code>//changing the url on the logo to redirect them\nfunction mb_login_url() { return home_url(); }\nadd_filter( 'login_headerurl', 'mb_login_url' );\n\n// changing the alt text on the logo to show your site name\nfunction mb_login_title() { return get_option( 'blogname' ); }\nadd_filter( 'login_headertitle', 'mb_login_title' );\n</code></pre>\n\n<hr>\n\n<h2>To change the Logo in Admin side login page</h2>\n\n<pre><code>function my_login_logo_one() { \n?> \n<style type=\"text/css\"> \nbody.login div#login h1 a {\nbackground-image: url(http://sitetitle.com/logo-1.png); \n}\n</style>\n<?php }\nadd_action( 'login_enqueue_scripts', 'my_login_logo_one' );\n</code></pre>\n"
},
{
"answer_id": 363359,
"author": "Niels Lange",
"author_id": 112118,
"author_profile": "https://wordpress.stackexchange.com/users/112118",
"pm_score": 1,
"selected": false,
"text": "<p>In case anyone else if facing the same issue, I created the plugin <a href=\"https://wordpress.org/plugins/smntcs-custom-logo-link/\" rel=\"nofollow noreferrer\">SMNTCS Custom Logo Link</a> a while ago, which works with all themes that have 100.000+ active installations. If the theme that you're using is not among those themes, simply create an issue on <a href=\"https://github.com/nielslange/smntcs-custom-logo-link/issues\" rel=\"nofollow noreferrer\">https://github.com/nielslange/smntcs-custom-logo-link/issues</a> and I'm happy to extend the plugin. </p>\n"
},
{
"answer_id": 368422,
"author": "Voltaki",
"author_id": 132144,
"author_profile": "https://wordpress.stackexchange.com/users/132144",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way is to add this jQuery code</p>\n\n<pre><code>jQuery(document).ready(function($){ \n $(\"a.logo-class\").attr(\"href\", \"https://google.com\");\n});\n</code></pre>\n"
},
{
"answer_id": 393707,
"author": "Adrian Laurenzi",
"author_id": 210612,
"author_profile": "https://wordpress.stackexchange.com/users/210612",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up taking the following Javascript-based approach which worked for my purposes. I am using the theme from <a href=\"https://theme.co/x\" rel=\"nofollow noreferrer\">https://theme.co/x</a>. I installed the Insert Headers and Footers plugin and then added the following Javascript (Footer section):</p>\n<pre><code><script>\n document.getElementsByClassName('x-brand')[0].setAttribute("href", "https://example.com");\n</script>\n</code></pre>\n<p>You will need to change the <code>'x-brand'</code> to point to the class of the logo href element specific for the given theme you are using.</p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57920/"
]
| I'm using a child theme based on 'Twenty Seventeen' and have created a custom post type ('review').
I want to make two Pages, one which lists 'reviews' and the other which lists a mixture of 'posts' and 'reviews' (ordered by recency).
For the first of those I've made a copy of Twenty Seventeen's `index.php`, as `page-reviews.php`, and added code like this at the start:
```
$args = array(
'post_type' => 'review',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 10,
);
$the_query = new WP_Query( $args );
```
Then, further down, replaced `have_posts()` and `the_post()` with `$the_query->have_posts()` and `$the_query->the_post()` respectively.
If I choose to use that template for a Page then it works in that the 'reviews' are listed, *but* the layout is all messed up. There are a lot of classes in the `<body>` which mess up the layout.
For example, the standard blog front page, using `index.php`, has these classes in its `<body>` and looks fine:
```
blog logged-in admin-bar hfeed has-header-image has-sidebar colors-light customize-support
```
While my custom page has these:
```
page-template page-template-page-postslist page-template-page-postslist-php page page-id-15071 logged-in admin-bar has-header-image page-two-column colors-light customize-support
```
How can I make a custom template that acts more like `index.php` in terms of the classes it adds? | The `login_headerurl` filter is for changing the logo url of login page, according to the [Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl).
To change the logo URL of your homepage, you will have to look into your theme's `header.php` file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.
Access your `header.php` file from `Appearance > Edit` in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want. |
256,726 | <ol>
<li>I have Zend framework 2 application (PHP), via which I want to use WP-CLI functionality. near Zend project I have WordPress project, which I want to maintain from Zend via WP-CLI. </li>
<li>I see in the docs that WP-CLI also written on PHP. I dreamed that I install WP-CLI via composer in root of my project and can use its classes there.</li>
<li>After installing via composer in WP-CLI's sources I see functions from WordPress (like as is_multisite and etc) and I little disappointed :).</li>
</ol>
<p>main question:
Can I in some way use WP-CLI sources directly from my Zend-project without calling commands via terminal?
for example (in abstract programming language):</p>
<pre><code>$command = new WP_CLI::command('command_name subcommand_name', $params, $assoc_params, .....);
$result = $command->execute();
</code></pre>
<p>Or WP-CLI was made only as part of the WordPress project as way for extending it's commands and it is unable to use them as I am trying?</p>
| [
{
"answer_id": 291803,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>WP_CLI</code> class has a <code>runcommand</code> method that launches a new child process to run a specified WP-CLI command. According to <a href=\"https://github.com/wp-cli/wp-cli/blob/0fd299de2292ffb4794b32db1edcbd4978fd650d/php/class-wp-cli.php#L1066-L1093\" rel=\"nofollow noreferrer\">the docs</a>, you can use it like this:</p>\n\n<pre><code>$options = array(\n 'return' => true, // Return 'STDOUT'; use 'all' for full object.\n 'parse' => 'json', // Parse captured STDOUT to JSON array.\n 'launch' => false, // Reuse the current process.\n 'exit_error' => true, // Halt script execution on error.\n);\n\n$plugins = WP_CLI::runcommand( 'plugin list --format=json', $options );\n</code></pre>\n"
},
{
"answer_id": 291805,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably unwise. WP-CLI is developed as a command line utility and might not maintain internal structure between releases.</p>\n\n<p>Since everything has to run as root in any case, there is no real difference between executing a WP-CLI command via a shell (A.K.A <code>exec</code> and its family of functions), or by calling whatever API. </p>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113499/"
]
| 1. I have Zend framework 2 application (PHP), via which I want to use WP-CLI functionality. near Zend project I have WordPress project, which I want to maintain from Zend via WP-CLI.
2. I see in the docs that WP-CLI also written on PHP. I dreamed that I install WP-CLI via composer in root of my project and can use its classes there.
3. After installing via composer in WP-CLI's sources I see functions from WordPress (like as is\_multisite and etc) and I little disappointed :).
main question:
Can I in some way use WP-CLI sources directly from my Zend-project without calling commands via terminal?
for example (in abstract programming language):
```
$command = new WP_CLI::command('command_name subcommand_name', $params, $assoc_params, .....);
$result = $command->execute();
```
Or WP-CLI was made only as part of the WordPress project as way for extending it's commands and it is unable to use them as I am trying? | This is probably unwise. WP-CLI is developed as a command line utility and might not maintain internal structure between releases.
Since everything has to run as root in any case, there is no real difference between executing a WP-CLI command via a shell (A.K.A `exec` and its family of functions), or by calling whatever API. |
256,733 | <p>Failing miserably at adding a custom column</p>
<pre><code>add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'column name');
$new_columns['categories'] = _x('Type', 'column name');
$new_columns['date'] = _x('Created', 'column name');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'categories':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
</code></pre>
<p><code>Type</code> column only ever shows <code>--</code> Yes, I have verified <code>$pt[0]->name</code> <code>var_dumps</code> what it actually should be.</p>
<p>So, what am I doing wrong here? I need the <code>Type</code> column to show my <code>pricing_type</code> value.</p>
<p><code>pricing</code> is a custom post type, while <code>pricing_type</code> is a custom taxonomy of the <code>pricing</code> post type.</p>
| [
{
"answer_id": 256734,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 2,
"selected": true,
"text": "<pre><code>add_action('manage_edit-pricing_columns', 'manage_pricing_columns');\nadd_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');\nfunction manage_pricing_columns($_columns) {\n $new_columns['cb'] = '<input type=\"checkbox\" />';\n $new_columns['title'] = _x('Pricing Item', 'wp');\n $new_columns['categories'] = _x('Type', 'wp');\n $new_columns['date'] = _x('Created', 'wp');\n return $new_columns;\n}\nfunction manage_pricing_custom_columns($column, $post_id){\n global $post;\n switch($_columns) {\n case 'pricing_type':\n $pt = get_the_terms( $post_id, 'pricing_type' );\n echo $pt[0]->name;\n break;\n default:\n break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 256735,
"author": "Kevin",
"author_id": 84711,
"author_profile": "https://wordpress.stackexchange.com/users/84711",
"pm_score": 0,
"selected": false,
"text": "<p>Or</p>\n\n<pre><code>add_action('manage_edit-pricing_columns', 'manage_pricing_columns');\nadd_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');\nfunction manage_pricing_columns($_columns) {\n $new_columns['cb'] = '<input type=\"checkbox\" />';\n $new_columns['title'] = _x('Pricing Item', 'column name');\n $new_columns['pricing_type'] = _x('Type', 'column name');\n $new_columns['date'] = _x('Created', 'column name');\n return $new_columns;\n}\nfunction manage_pricing_custom_columns($column){\n global $post;\n switch($column) {\n case 'pricing_type':\n $pt = get_the_terms( $post->ID, 'pricing_type' );\n echo $pt[0]->name;\n break;\n default:\n break;\n }\n}\n</code></pre>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84711/"
]
| Failing miserably at adding a custom column
```
add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'column name');
$new_columns['categories'] = _x('Type', 'column name');
$new_columns['date'] = _x('Created', 'column name');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'categories':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
```
`Type` column only ever shows `--` Yes, I have verified `$pt[0]->name` `var_dumps` what it actually should be.
So, what am I doing wrong here? I need the `Type` column to show my `pricing_type` value.
`pricing` is a custom post type, while `pricing_type` is a custom taxonomy of the `pricing` post type. | ```
add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'wp');
$new_columns['categories'] = _x('Type', 'wp');
$new_columns['date'] = _x('Created', 'wp');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'pricing_type':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
``` |
256,751 | <p>I have a custom post type <code>event</code> in WordPress, and I need to query upcoming <code>event</code> <code>posts</code> comparing <code>$current_date</code>.</p>
<p>Query conditions are :</p>
<ul>
<li><code>start_date</code> is a valid <code>date</code> always</li>
<li><code>end_date</code> can be a valid <code>date</code> or <code>null</code> or <code>empty</code> string.</li>
<li>IF <code>end_date</code> is a valid <code>date</code> in db record then compare <code>end_date >= $current_date</code></li>
<li>ELSE IF <code>end_date</code> is <code>null</code> or <code>empty</code> then compare <code>start_date >=$current_date</code>.</li>
</ul>
<p>Now If <code>end_date</code> was not optional , I could use below code to get desired results.</p>
<pre><code>$args= array();
$args['post_type'] = "event";
$args['meta_query'] = array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date("Ymd",$current_date),
)
);
$post_query = new WP_Query();
$posts_list = $post_query->query($args);
</code></pre>
<p>My problem is, how do I handle optional <code>end_date</code> in above code.</p>
<p>Thanks in advance.</p>
<p>Edit:
Reformatted code and text above to make it more clear</p>
| [
{
"answer_id": 256753,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// $startday, $endday - format YYYY-MM-DD and field format: YYYY-MM-DD \n $args= array(); \n $args['post_type'] = \"event\";\n $args['meta_query'] = array(\n relation' => 'OR', \n array(\n 'key' => 'end_date',\n 'value' => array( $startday, $endday ),\n 'type' => 'DATE',\n 'compare' => 'BETWEEN'\n ), \n array(\n 'key' => 'start_date',\n 'value' => array( $startday, $endday ),\n 'type' => 'DATE',\n 'compare' => 'BETWEEN'\n ) \n );\n $post_query = new WP_Query();\n $posts_list = $post_query->query($args);\n</code></pre>\n\n<p>Perhaps again I did not understand you</p>\n"
},
{
"answer_id": 256781,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 1,
"selected": false,
"text": "<p>I think I know what you are going through ... I recently had to deal with a situation where I was (among other things) comparing a meta value that may or may not exist.</p>\n\n<p>The solution I found involved a very crazy SQl statment, with a WHERE IF clause.</p>\n\n<p>In your case, it could look something like this (explanation below):</p>\n\n<pre><code>global $wpdb;\n\n// prepare SQL statement\n$sql = $wpdb->prepare(\"\n SELECT * \n FROM $wpdb->posts\n INNER JOIN $wpdb->postmeta\n ON $wpdb->posts.ID = $wpdb->postmeta.post_id\n WHERE post_type = 'event'\n AND post_status = 'publish'\n AND IF(\n (\n SELECT COUNT( post_id) \n FROM $wpdb->postmeta \n WHERE meta_key = 'end_date' \n AND post_id = ID \n ) > 0,\n meta_key = 'end_date',\n meta_key = 'start_date'\n )\n AND meta_value >= %s\n LIMIT %d\n\", date( 'Ymd'), 10 );\n\n// get results\n$results = $wpdb->get_results( $sql );\n\n// iterate through results\nforeach( $results as $result ) {\n setup_postdata( $result );\n\n // your loop\n}\n</code></pre>\n\n<p>(Note this was tested on a similar setup, but not with your exact post meta fields. Might need a bit of tweaking).</p>\n\n<p>First, we get the global <code>wpdb</code> variable, to access the raw wordpress db.</p>\n\n<p>Then we prepare an SQL query which gets posts and joins them with post meta values (for comparison)</p>\n\n<p>BUT. Here is the trick. The WHERE Statement has both <code>meta_key</code>, <code>meta_value</code>.</p>\n\n<p>We know <code>meta_value</code> is always the same, which is the current date.</p>\n\n<p>So for <code>meta_key</code> we run an IF statement that checks how many post meta rows the current post ID has where its meta key is equal to 'end_date'.</p>\n\n<p>If it has more than 0 rows, then set <code>meta_key</code> to 'end_date' (second argument in the IF function), otherwise set it to 'start_date' (third argument).</p>\n\n<p>We also check post type and make sure they are published and limit the return to 10 (or whatever you'd like).</p>\n\n<p>Finally, we fetch the results to use them as we please.</p>\n\n<p>I know its a bit of a hack, but it works. Its also a bit slow, so might be worth caching the results</p>\n\n<p>Hope that's what you are looking for! And if you find a better solution, please let me know :)</p>\n"
},
{
"answer_id": 257372,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 4,
"selected": true,
"text": "<p>There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have <a href=\"https://core.trac.wordpress.org/ticket/29642\" rel=\"noreferrer\">supported complex/nested meta queries</a>. So you can craft a query like this:</p>\n\n<pre><code> $args['meta_query'] = array(\n // Use an OR relationship between the query in this array and the one in\n // the next array. (AND is the default.)\n 'relation' => 'OR',\n // If an end_date exists, check that it is upcoming.\n array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => date( 'Ymd', $current_date ),\n ),\n // OR!\n array(\n // A nested set of conditions for when the above condition is false.\n array(\n // We use another, nested set of conditions, for if the end_date\n // value is empty, OR if it is null/not set at all. \n 'relation' => 'OR',\n array(\n 'key' => 'end_date',\n 'compare' => '=',\n 'value' => '',\n ),\n array(\n 'key' => 'end_date',\n 'compare' => 'NOT EXISTS',\n ),\n ),\n // AND, if the start date is upcoming.\n array(\n 'key' => 'start_date',\n 'compare' => '>=',\n 'value' => date( 'Ymd', $current_date ),\n ),\n ),\n );\n</code></pre>\n\n<p>I have tested this, and it works perfectly. My PHPUnit testcase:</p>\n\n<pre><code>/**\n * Tests something.\n */\nclass My_Plugin_Test extends WP_UnitTestCase {\n\n public function test_wpse() {\n\n $current_time = current_time( 'timestamp' );\n $current_date = date( 'Ymd', $current_time );\n $yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );\n\n $post_ids = $this->factory->post->create_many( 6 );\n\n $post_with_end_past = $post_ids[0];\n $post_with_end_now = $post_ids[1];\n $post_empty_end_past = $post_ids[2];\n $post_empty_end_now = $post_ids[3];\n $post_null_end_past = $post_ids[4];\n $post_null_end_now = $post_ids[5];\n\n // This post has an end date in the past.\n update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );\n update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );\n\n // This post has an end date in the present.\n update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );\n update_post_meta( $post_with_end_now, 'end_date', $current_date );\n\n // This post has no end date, but a start date in the past.\n update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );\n update_post_meta( $post_empty_end_past, 'end_date', '' );\n\n // This post has an empty end date, but the start date is now.\n update_post_meta( $post_empty_end_now, 'start_date', $current_date );\n update_post_meta( $post_empty_end_now, 'end_date', '' );\n\n // This post has no end date set at all, and the start date is past.\n update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );\n\n // This post has no end date set at all, but the start date is now.\n update_post_meta( $post_null_end_now, 'start_date', $current_date );\n\n $args = array();\n $args['fields'] = 'ids';\n $args['meta_query'] = array(\n // Use an OR relationship between the query in this array and the one in\n // the next array. (AND is the default.)\n 'relation' => 'OR',\n // If an end_date exists, check that it is upcoming.\n array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => $current_date,\n ),\n // OR!\n array(\n // If an end_date does not exist.\n array(\n // We use another, nested set of conditions, for if the end_date\n // value is empty, OR if it is null/not set at all.\n 'relation' => 'OR',\n array(\n 'key' => 'end_date',\n 'compare' => '=',\n 'value' => '',\n ),\n array(\n 'key' => 'end_date',\n 'compare' => 'NOT EXISTS',\n ),\n ),\n // AND, if the start date is upcoming.\n array(\n 'key' => 'start_date',\n 'compare' => '>=',\n 'value' => $current_date,\n ),\n ),\n );\n\n $post_query = new WP_Query();\n $posts_list = $post_query->query( $args );\n\n // Only the \"now\" posts should be returned.\n $this->assertSame(\n array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )\n , $posts_list\n );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257426,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>I'm seeing some awesome solutions, here; but could we be overthinking it?</p>\n\n<p>Would this work...</p>\n\n<pre><code>$args= array();\n$args['post_type'] = \"event\";\n$args['meta_query'] = array();\n\nif (!empty($end_date) && strtotime($end_date)) {\n $args['meta_query'][] = array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => date(\"Ymd\",$current_date),\n );\n} elseif (!empty($start_date) && strtotime($start_date)) {\n $args['meta_query'][] = array(\n 'key' => 'start_date ',\n 'compare' => '>=',\n 'value' => date(\"Ymd\",$current_date),\n )\n}\n\n$post_query = new WP_Query();\n$posts_list = $post_query->query($args);\n</code></pre>\n"
},
{
"answer_id": 257578,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 0,
"selected": false,
"text": "<p>I Make this query for your issue. Kindly check it. Let me Know It's working?.</p>\n\n<pre><code>$global $wpdb;\n\n$qry = \"SELECT * from $wpdb->posts t1 WHERE t1.post_type='event' and t1.ID IN (SELECT t2.post_id from $wpdb->postmeta t2 WHERE ( CASE WHEN t2.meta_key = 'end_date' AND t2.meta_value IS NULL THEN t2.meta_key = 'start_date' AND t2.meta_value >= '\". $currentdate .\"' ELSE t2.meta_key = 'end_date' AND t2.meta_key >= '\". $currentdate .\"' END ))\"\n\n$post_query = new WP_Query();\n$posts_list = $post_query->query($qry);\n</code></pre>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73154/"
]
| I have a custom post type `event` in WordPress, and I need to query upcoming `event` `posts` comparing `$current_date`.
Query conditions are :
* `start_date` is a valid `date` always
* `end_date` can be a valid `date` or `null` or `empty` string.
* IF `end_date` is a valid `date` in db record then compare `end_date >= $current_date`
* ELSE IF `end_date` is `null` or `empty` then compare `start_date >=$current_date`.
Now If `end_date` was not optional , I could use below code to get desired results.
```
$args= array();
$args['post_type'] = "event";
$args['meta_query'] = array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date("Ymd",$current_date),
)
);
$post_query = new WP_Query();
$posts_list = $post_query->query($args);
```
My problem is, how do I handle optional `end_date` in above code.
Thanks in advance.
Edit:
Reformatted code and text above to make it more clear | There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have [supported complex/nested meta queries](https://core.trac.wordpress.org/ticket/29642). So you can craft a query like this:
```
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
// OR!
array(
// A nested set of conditions for when the above condition is false.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
),
);
```
I have tested this, and it works perfectly. My PHPUnit testcase:
```
/**
* Tests something.
*/
class My_Plugin_Test extends WP_UnitTestCase {
public function test_wpse() {
$current_time = current_time( 'timestamp' );
$current_date = date( 'Ymd', $current_time );
$yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );
$post_ids = $this->factory->post->create_many( 6 );
$post_with_end_past = $post_ids[0];
$post_with_end_now = $post_ids[1];
$post_empty_end_past = $post_ids[2];
$post_empty_end_now = $post_ids[3];
$post_null_end_past = $post_ids[4];
$post_null_end_now = $post_ids[5];
// This post has an end date in the past.
update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );
// This post has an end date in the present.
update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_now, 'end_date', $current_date );
// This post has no end date, but a start date in the past.
update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_empty_end_past, 'end_date', '' );
// This post has an empty end date, but the start date is now.
update_post_meta( $post_empty_end_now, 'start_date', $current_date );
update_post_meta( $post_empty_end_now, 'end_date', '' );
// This post has no end date set at all, and the start date is past.
update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );
// This post has no end date set at all, but the start date is now.
update_post_meta( $post_null_end_now, 'start_date', $current_date );
$args = array();
$args['fields'] = 'ids';
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $current_date,
),
// OR!
array(
// If an end_date does not exist.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => $current_date,
),
),
);
$post_query = new WP_Query();
$posts_list = $post_query->query( $args );
// Only the "now" posts should be returned.
$this->assertSame(
array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )
, $posts_list
);
}
}
``` |
256,754 | <p>I am trying to edit theme editor to edit files on wordpress, but I get the error about, the file is not writable. So now I want to give the account write permissions on the file, but I don't know which user account wordpress runs as on the website when editing files. Does anyone know?</p>
<p>Thanks</p>
| [
{
"answer_id": 256753,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// $startday, $endday - format YYYY-MM-DD and field format: YYYY-MM-DD \n $args= array(); \n $args['post_type'] = \"event\";\n $args['meta_query'] = array(\n relation' => 'OR', \n array(\n 'key' => 'end_date',\n 'value' => array( $startday, $endday ),\n 'type' => 'DATE',\n 'compare' => 'BETWEEN'\n ), \n array(\n 'key' => 'start_date',\n 'value' => array( $startday, $endday ),\n 'type' => 'DATE',\n 'compare' => 'BETWEEN'\n ) \n );\n $post_query = new WP_Query();\n $posts_list = $post_query->query($args);\n</code></pre>\n\n<p>Perhaps again I did not understand you</p>\n"
},
{
"answer_id": 256781,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 1,
"selected": false,
"text": "<p>I think I know what you are going through ... I recently had to deal with a situation where I was (among other things) comparing a meta value that may or may not exist.</p>\n\n<p>The solution I found involved a very crazy SQl statment, with a WHERE IF clause.</p>\n\n<p>In your case, it could look something like this (explanation below):</p>\n\n<pre><code>global $wpdb;\n\n// prepare SQL statement\n$sql = $wpdb->prepare(\"\n SELECT * \n FROM $wpdb->posts\n INNER JOIN $wpdb->postmeta\n ON $wpdb->posts.ID = $wpdb->postmeta.post_id\n WHERE post_type = 'event'\n AND post_status = 'publish'\n AND IF(\n (\n SELECT COUNT( post_id) \n FROM $wpdb->postmeta \n WHERE meta_key = 'end_date' \n AND post_id = ID \n ) > 0,\n meta_key = 'end_date',\n meta_key = 'start_date'\n )\n AND meta_value >= %s\n LIMIT %d\n\", date( 'Ymd'), 10 );\n\n// get results\n$results = $wpdb->get_results( $sql );\n\n// iterate through results\nforeach( $results as $result ) {\n setup_postdata( $result );\n\n // your loop\n}\n</code></pre>\n\n<p>(Note this was tested on a similar setup, but not with your exact post meta fields. Might need a bit of tweaking).</p>\n\n<p>First, we get the global <code>wpdb</code> variable, to access the raw wordpress db.</p>\n\n<p>Then we prepare an SQL query which gets posts and joins them with post meta values (for comparison)</p>\n\n<p>BUT. Here is the trick. The WHERE Statement has both <code>meta_key</code>, <code>meta_value</code>.</p>\n\n<p>We know <code>meta_value</code> is always the same, which is the current date.</p>\n\n<p>So for <code>meta_key</code> we run an IF statement that checks how many post meta rows the current post ID has where its meta key is equal to 'end_date'.</p>\n\n<p>If it has more than 0 rows, then set <code>meta_key</code> to 'end_date' (second argument in the IF function), otherwise set it to 'start_date' (third argument).</p>\n\n<p>We also check post type and make sure they are published and limit the return to 10 (or whatever you'd like).</p>\n\n<p>Finally, we fetch the results to use them as we please.</p>\n\n<p>I know its a bit of a hack, but it works. Its also a bit slow, so might be worth caching the results</p>\n\n<p>Hope that's what you are looking for! And if you find a better solution, please let me know :)</p>\n"
},
{
"answer_id": 257372,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 4,
"selected": true,
"text": "<p>There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have <a href=\"https://core.trac.wordpress.org/ticket/29642\" rel=\"noreferrer\">supported complex/nested meta queries</a>. So you can craft a query like this:</p>\n\n<pre><code> $args['meta_query'] = array(\n // Use an OR relationship between the query in this array and the one in\n // the next array. (AND is the default.)\n 'relation' => 'OR',\n // If an end_date exists, check that it is upcoming.\n array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => date( 'Ymd', $current_date ),\n ),\n // OR!\n array(\n // A nested set of conditions for when the above condition is false.\n array(\n // We use another, nested set of conditions, for if the end_date\n // value is empty, OR if it is null/not set at all. \n 'relation' => 'OR',\n array(\n 'key' => 'end_date',\n 'compare' => '=',\n 'value' => '',\n ),\n array(\n 'key' => 'end_date',\n 'compare' => 'NOT EXISTS',\n ),\n ),\n // AND, if the start date is upcoming.\n array(\n 'key' => 'start_date',\n 'compare' => '>=',\n 'value' => date( 'Ymd', $current_date ),\n ),\n ),\n );\n</code></pre>\n\n<p>I have tested this, and it works perfectly. My PHPUnit testcase:</p>\n\n<pre><code>/**\n * Tests something.\n */\nclass My_Plugin_Test extends WP_UnitTestCase {\n\n public function test_wpse() {\n\n $current_time = current_time( 'timestamp' );\n $current_date = date( 'Ymd', $current_time );\n $yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );\n\n $post_ids = $this->factory->post->create_many( 6 );\n\n $post_with_end_past = $post_ids[0];\n $post_with_end_now = $post_ids[1];\n $post_empty_end_past = $post_ids[2];\n $post_empty_end_now = $post_ids[3];\n $post_null_end_past = $post_ids[4];\n $post_null_end_now = $post_ids[5];\n\n // This post has an end date in the past.\n update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );\n update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );\n\n // This post has an end date in the present.\n update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );\n update_post_meta( $post_with_end_now, 'end_date', $current_date );\n\n // This post has no end date, but a start date in the past.\n update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );\n update_post_meta( $post_empty_end_past, 'end_date', '' );\n\n // This post has an empty end date, but the start date is now.\n update_post_meta( $post_empty_end_now, 'start_date', $current_date );\n update_post_meta( $post_empty_end_now, 'end_date', '' );\n\n // This post has no end date set at all, and the start date is past.\n update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );\n\n // This post has no end date set at all, but the start date is now.\n update_post_meta( $post_null_end_now, 'start_date', $current_date );\n\n $args = array();\n $args['fields'] = 'ids';\n $args['meta_query'] = array(\n // Use an OR relationship between the query in this array and the one in\n // the next array. (AND is the default.)\n 'relation' => 'OR',\n // If an end_date exists, check that it is upcoming.\n array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => $current_date,\n ),\n // OR!\n array(\n // If an end_date does not exist.\n array(\n // We use another, nested set of conditions, for if the end_date\n // value is empty, OR if it is null/not set at all.\n 'relation' => 'OR',\n array(\n 'key' => 'end_date',\n 'compare' => '=',\n 'value' => '',\n ),\n array(\n 'key' => 'end_date',\n 'compare' => 'NOT EXISTS',\n ),\n ),\n // AND, if the start date is upcoming.\n array(\n 'key' => 'start_date',\n 'compare' => '>=',\n 'value' => $current_date,\n ),\n ),\n );\n\n $post_query = new WP_Query();\n $posts_list = $post_query->query( $args );\n\n // Only the \"now\" posts should be returned.\n $this->assertSame(\n array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )\n , $posts_list\n );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257426,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>I'm seeing some awesome solutions, here; but could we be overthinking it?</p>\n\n<p>Would this work...</p>\n\n<pre><code>$args= array();\n$args['post_type'] = \"event\";\n$args['meta_query'] = array();\n\nif (!empty($end_date) && strtotime($end_date)) {\n $args['meta_query'][] = array(\n 'key' => 'end_date',\n 'compare' => '>=',\n 'value' => date(\"Ymd\",$current_date),\n );\n} elseif (!empty($start_date) && strtotime($start_date)) {\n $args['meta_query'][] = array(\n 'key' => 'start_date ',\n 'compare' => '>=',\n 'value' => date(\"Ymd\",$current_date),\n )\n}\n\n$post_query = new WP_Query();\n$posts_list = $post_query->query($args);\n</code></pre>\n"
},
{
"answer_id": 257578,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 0,
"selected": false,
"text": "<p>I Make this query for your issue. Kindly check it. Let me Know It's working?.</p>\n\n<pre><code>$global $wpdb;\n\n$qry = \"SELECT * from $wpdb->posts t1 WHERE t1.post_type='event' and t1.ID IN (SELECT t2.post_id from $wpdb->postmeta t2 WHERE ( CASE WHEN t2.meta_key = 'end_date' AND t2.meta_value IS NULL THEN t2.meta_key = 'start_date' AND t2.meta_value >= '\". $currentdate .\"' ELSE t2.meta_key = 'end_date' AND t2.meta_key >= '\". $currentdate .\"' END ))\"\n\n$post_query = new WP_Query();\n$posts_list = $post_query->query($qry);\n</code></pre>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113339/"
]
| I am trying to edit theme editor to edit files on wordpress, but I get the error about, the file is not writable. So now I want to give the account write permissions on the file, but I don't know which user account wordpress runs as on the website when editing files. Does anyone know?
Thanks | There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have [supported complex/nested meta queries](https://core.trac.wordpress.org/ticket/29642). So you can craft a query like this:
```
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
// OR!
array(
// A nested set of conditions for when the above condition is false.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
),
);
```
I have tested this, and it works perfectly. My PHPUnit testcase:
```
/**
* Tests something.
*/
class My_Plugin_Test extends WP_UnitTestCase {
public function test_wpse() {
$current_time = current_time( 'timestamp' );
$current_date = date( 'Ymd', $current_time );
$yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );
$post_ids = $this->factory->post->create_many( 6 );
$post_with_end_past = $post_ids[0];
$post_with_end_now = $post_ids[1];
$post_empty_end_past = $post_ids[2];
$post_empty_end_now = $post_ids[3];
$post_null_end_past = $post_ids[4];
$post_null_end_now = $post_ids[5];
// This post has an end date in the past.
update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );
// This post has an end date in the present.
update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_now, 'end_date', $current_date );
// This post has no end date, but a start date in the past.
update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_empty_end_past, 'end_date', '' );
// This post has an empty end date, but the start date is now.
update_post_meta( $post_empty_end_now, 'start_date', $current_date );
update_post_meta( $post_empty_end_now, 'end_date', '' );
// This post has no end date set at all, and the start date is past.
update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );
// This post has no end date set at all, but the start date is now.
update_post_meta( $post_null_end_now, 'start_date', $current_date );
$args = array();
$args['fields'] = 'ids';
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $current_date,
),
// OR!
array(
// If an end_date does not exist.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => $current_date,
),
),
);
$post_query = new WP_Query();
$posts_list = $post_query->query( $args );
// Only the "now" posts should be returned.
$this->assertSame(
array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )
, $posts_list
);
}
}
``` |
256,760 | <p>I have a custom taxonomy, called albums.</p>
<p>I need to be able to text search the taxonomy term title, obviously this isn't default WP Search. Just wondering how I'd best tackle this? </p>
<p>Say there is an album called 'Football Hits',</p>
<p>I start typing foot and search that, all I need it to appear is the album title and the permalink.</p>
<p>Thanks!</p>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">tax_query</a>\" part of WP_Query. Here's an example from the Codex, adapted to your needs:</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title'];\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I have not tested this, but in theory, I think it could work. To match anything that contains \"foot\":</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title']; // say the user entered 'foot'\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title,\n 'operator' => 'LIKE'\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 256772,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 5,
"selected": true,
"text": "<pre><code>// We get a list taxonomies on the search box\nfunction get_tax_by_search($search_text){\n\n$args = array(\n 'taxonomy' => array( 'my_tax' ), // taxonomy name\n 'orderby' => 'id', \n 'order' => 'ASC',\n 'hide_empty' => true,\n 'fields' => 'all',\n 'name__like' => $search_text\n); \n\n$terms = get_terms( $args );\n\n $count = count($terms);\n if($count > 0){\n echo \"<ul>\";\n foreach ($terms as $term) {\n echo \"<li><a href='\".get_term_link( $term ).\"'>\".$term->name.\"</a></li>\";\n\n }\n echo \"</ul>\";\n }\n\n}\n\n// sample\nget_tax_by_search('Foo');\n</code></pre>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113513/"
]
| I have a custom taxonomy, called albums.
I need to be able to text search the taxonomy term title, obviously this isn't default WP Search. Just wondering how I'd best tackle this?
Say there is an album called 'Football Hits',
I start typing foot and search that, all I need it to appear is the album title and the permalink.
Thanks! | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,777 | <pre><code><?php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order'=> 'DESC', // sort descending
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title());
}
}
// Restore original post data.
wp_reset_postdata();
?>
</code></pre>
<p>This is the first time i've worked with wpquery.</p>
<p>Two questions</p>
<ol>
<li>how do i add a comma each item but the last?</li>
<li>How could i've written this better?</li>
</ol>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">tax_query</a>\" part of WP_Query. Here's an example from the Codex, adapted to your needs:</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title'];\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I have not tested this, but in theory, I think it could work. To match anything that contains \"foot\":</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title']; // say the user entered 'foot'\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title,\n 'operator' => 'LIKE'\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 256772,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 5,
"selected": true,
"text": "<pre><code>// We get a list taxonomies on the search box\nfunction get_tax_by_search($search_text){\n\n$args = array(\n 'taxonomy' => array( 'my_tax' ), // taxonomy name\n 'orderby' => 'id', \n 'order' => 'ASC',\n 'hide_empty' => true,\n 'fields' => 'all',\n 'name__like' => $search_text\n); \n\n$terms = get_terms( $args );\n\n $count = count($terms);\n if($count > 0){\n echo \"<ul>\";\n foreach ($terms as $term) {\n echo \"<li><a href='\".get_term_link( $term ).\"'>\".$term->name.\"</a></li>\";\n\n }\n echo \"</ul>\";\n }\n\n}\n\n// sample\nget_tax_by_search('Foo');\n</code></pre>\n"
}
]
| 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113103/"
]
| ```
<?php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order'=> 'DESC', // sort descending
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title());
}
}
// Restore original post data.
wp_reset_postdata();
?>
```
This is the first time i've worked with wpquery.
Two questions
1. how do i add a comma each item but the last?
2. How could i've written this better? | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,804 | <p>I'm using WP API to get posts in my application and I'm trying to exclude some posts from query using <code>filter[post__not_in]</code>.
after removing <code>filter</code> in WP <strong>4.7</strong>, I'm using <code>WP REST API filter parameter</code> plugin to get it back. and it works for all parameters but for <code>post__not_in</code> it's not effecting at all, I still get all posts.</p>
<p>I saw some closed issues about this on WP API repo on github, they said that <code>post__not_in</code> are not allowed for unauthenticated requests, I also found merged PR claimed that they fixed it, but I tried to use this function</p>
<pre><code>add_filter( 'query_vars', function( $vars ){
$vars[] = 'post__in';
$vars[] = 'post__not_in';
return $vars;
});
</code></pre>
<p>but now whatever I pass to <code>post__not_in</code> I get empty response</p>
<p>any ideas how to exclude post in WP API?</p>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">tax_query</a>\" part of WP_Query. Here's an example from the Codex, adapted to your needs:</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title'];\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I have not tested this, but in theory, I think it could work. To match anything that contains \"foot\":</p>\n\n<pre><code><ul>\n<?php\n\nglobal $post;\n$album_title = $_GET['album-title']; // say the user entered 'foot'\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 5,\n 'tax_query' => array( // NOTE: array of arrays!\n array(\n 'taxonomy' => 'albums',\n 'field' => 'name',\n 'terms' => $album_title,\n 'operator' => 'LIKE'\n )\n )\n);\n\n$myposts = get_posts( $args );\nforeach ( $myposts as $post ) : setup_postdata( $post ); ?>\n <li>\n <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>\n </li>\n<?php endforeach; \nwp_reset_postdata();?>\n\n</ul>\n</code></pre>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 256772,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 5,
"selected": true,
"text": "<pre><code>// We get a list taxonomies on the search box\nfunction get_tax_by_search($search_text){\n\n$args = array(\n 'taxonomy' => array( 'my_tax' ), // taxonomy name\n 'orderby' => 'id', \n 'order' => 'ASC',\n 'hide_empty' => true,\n 'fields' => 'all',\n 'name__like' => $search_text\n); \n\n$terms = get_terms( $args );\n\n $count = count($terms);\n if($count > 0){\n echo \"<ul>\";\n foreach ($terms as $term) {\n echo \"<li><a href='\".get_term_link( $term ).\"'>\".$term->name.\"</a></li>\";\n\n }\n echo \"</ul>\";\n }\n\n}\n\n// sample\nget_tax_by_search('Foo');\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52831/"
]
| I'm using WP API to get posts in my application and I'm trying to exclude some posts from query using `filter[post__not_in]`.
after removing `filter` in WP **4.7**, I'm using `WP REST API filter parameter` plugin to get it back. and it works for all parameters but for `post__not_in` it's not effecting at all, I still get all posts.
I saw some closed issues about this on WP API repo on github, they said that `post__not_in` are not allowed for unauthenticated requests, I also found merged PR claimed that they fixed it, but I tried to use this function
```
add_filter( 'query_vars', function( $vars ){
$vars[] = 'post__in';
$vars[] = 'post__not_in';
return $vars;
});
```
but now whatever I pass to `post__not_in` I get empty response
any ideas how to exclude post in WP API? | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,819 | <p>So I have a css file :<br>
<a href="https://i.stack.imgur.com/eHgBm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eHgBm.png" alt="CSS File" /></a></p>
<p>I also have enqueued it, :
<a href="https://i.stack.imgur.com/dB2fV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dB2fV.png" alt="Functions.php" /></a>
When I activate the theme, and try to view my page, no css is on it, Foundation is working, normalize is working, but not my css file, when I inspect element it's empty, and I don't know what I have to do.. ( The global.css source file in Inspect Element is empty, Foundation & normalize is not. )</p>
<p>Not allowed to post a 3rd link, but don't really think I need to show you a google chrome inspect element thing anyways..</p>
<p>Would really appriciate any help!</p>
| [
{
"answer_id": 256820,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 2,
"selected": false,
"text": "<p>it looks like your forgot a slash before <code>css/global.css</code>. The others are fine.</p>\n\n<p>Should read </p>\n\n<pre><code>get_template_directory_uri() . '/css/global.css'\n</code></pre>\n\n<p>Let me know if it works!</p>\n"
},
{
"answer_id": 256822,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": true,
"text": "<p>In a quick view, the arguments you use in <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_style()</code></a> are not correct for global.css. The third parameter is used to declare the dependencies and you have set that parameter to the string <code>'false'</code> but it should be an array. If the CSS does not depend on another CSS, use an empty array.</p>\n\n<p>In your case, I guess that the global.css depends on the other css you are lodaing (foundation, normalize, etc), so you should declare those dependencies.</p>\n\n<p>You are using the fourth parameter incorrectly too. The fourth parameter is used to specified the version. <code>'all'</code> seems not a version. If you don't want to declare a version, use <code>null</code>, but I think it is good to declare the version in all the CSS files you are loading. For example, if you use some browser cache and update the foundation CSS, the upade won't be sent to the users that have the CSS already cached in their browsers. If you declare the version, the URL will change after the update and the users will get the new CSS version.</p>\n\n<p>There is also a missing <code>/</code> in the URL (noted by Pedro in his answer).</p>\n\n<pre><code>wp_enqueue_style( 'venix_css', get_template_directory_uri() . '/css/global.css', array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );\n</code></pre>\n\n<p>Also, since WordPress 4.7, it is better if you use <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\"><code>get_theme_file_uri()</code></a> instead of <code>get_template_directory_uri()</code>. The new function is more flexible and allows child themes to override parent theme files easily.</p>\n\n<pre><code>wp_enqueue_style( 'venix_css', get_theme_file_uri( 'css/global.css' ) , array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256819",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113551/"
]
| So I have a css file :
[](https://i.stack.imgur.com/eHgBm.png)
I also have enqueued it, :
[](https://i.stack.imgur.com/dB2fV.png)
When I activate the theme, and try to view my page, no css is on it, Foundation is working, normalize is working, but not my css file, when I inspect element it's empty, and I don't know what I have to do.. ( The global.css source file in Inspect Element is empty, Foundation & normalize is not. )
Not allowed to post a 3rd link, but don't really think I need to show you a google chrome inspect element thing anyways..
Would really appriciate any help! | In a quick view, the arguments you use in [`wp_enqueue_style()`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) are not correct for global.css. The third parameter is used to declare the dependencies and you have set that parameter to the string `'false'` but it should be an array. If the CSS does not depend on another CSS, use an empty array.
In your case, I guess that the global.css depends on the other css you are lodaing (foundation, normalize, etc), so you should declare those dependencies.
You are using the fourth parameter incorrectly too. The fourth parameter is used to specified the version. `'all'` seems not a version. If you don't want to declare a version, use `null`, but I think it is good to declare the version in all the CSS files you are loading. For example, if you use some browser cache and update the foundation CSS, the upade won't be sent to the users that have the CSS already cached in their browsers. If you declare the version, the URL will change after the update and the users will get the new CSS version.
There is also a missing `/` in the URL (noted by Pedro in his answer).
```
wp_enqueue_style( 'venix_css', get_template_directory_uri() . '/css/global.css', array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );
```
Also, since WordPress 4.7, it is better if you use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) instead of `get_template_directory_uri()`. The new function is more flexible and allows child themes to override parent theme files easily.
```
wp_enqueue_style( 'venix_css', get_theme_file_uri( 'css/global.css' ) , array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );
``` |
256,830 | <p>I am trying to programmatically add multiple images to media library, I uploaded the images to <code>wp-content/uploads</code>, now I try to use <code>wp_insert_attachement</code>.</p>
<p>Here's the code, however it's not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.</p>
<pre><code>$filename_array = array(
'article1.jpg',
'article2.jpg',
);
// The ID of the post this attachment is for.
$parent_post_id = 0;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach ($filename_array as $filename) {
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
</code></pre>
| [
{
"answer_id": 256834,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 6,
"selected": true,
"text": "<pre><code>$image_url = 'adress img';\n\n$upload_dir = wp_upload_dir();\n\n$image_data = file_get_contents( $image_url );\n\n$filename = basename( $image_url );\n\nif ( wp_mkdir_p( $upload_dir['path'] ) ) {\n $file = $upload_dir['path'] . '/' . $filename;\n}\nelse {\n $file = $upload_dir['basedir'] . '/' . $filename;\n}\n\nfile_put_contents( $file, $image_data );\n\n$wp_filetype = wp_check_filetype( $filename, null );\n\n$attachment = array(\n 'post_mime_type' => $wp_filetype['type'],\n 'post_title' => sanitize_file_name( $filename ),\n 'post_content' => '',\n 'post_status' => 'inherit'\n);\n\n$attach_id = wp_insert_attachment( $attachment, $file );\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\n$attach_data = wp_generate_attachment_metadata( $attach_id, $file );\nwp_update_attachment_metadata( $attach_id, $attach_data );\n</code></pre>\n"
},
{
"answer_id": 320994,
"author": "Lance Cleveland",
"author_id": 11553,
"author_profile": "https://wordpress.stackexchange.com/users/11553",
"pm_score": 3,
"selected": false,
"text": "<p>I had issues with @TrubinE's solution where image files were not getting loaded.</p>\n\n<p>Here is a complete example that worked for me: <a href=\"https://gist.github.com/m1r0/f22d5237ee93bcccb0d9\" rel=\"noreferrer\">https://gist.github.com/m1r0/f22d5237ee93bcccb0d9</a></p>\n\n<p>This is a similar idea but use the WP HTTP library to fetch the content versus file_get_contents(). Here is the content of the github gist solution from m1r0:</p>\n\n<pre><code> if( !class_exists( 'WP_Http' ) )\n include_once( ABSPATH . WPINC . '/class-http.php' );\n $http = new WP_Http();\n $response = $http->request( $meta[ 'image_url' ] );\n if( $response['response']['code'] != 200 ) {\n return false;\n }\n $upload = wp_upload_bits( basename($meta[ 'image_url' ]), null, $response['body'] );\n if( !empty( $upload['error'] ) ) {\n return false;\n }\n $file_path = $upload['file'];\n $file_name = basename( $file_path );\n $file_type = wp_check_filetype( $file_name, null );\n $attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );\n $wp_upload_dir = wp_upload_dir();\n\n $post_info = array(\n 'guid' => $wp_upload_dir['url'] . '/' . $file_name,\n 'post_mime_type' => $file_type['type'],\n 'post_title' => $attachment_title,\n 'post_content' => '',\n 'post_status' => 'inherit',\n );\n\n $attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );\n wp_update_attachment_metadata( $attach_id, $attach_data );\n return $attach_id; code here\n</code></pre>\n"
},
{
"answer_id": 371360,
"author": "Paul Schreiber",
"author_id": 8591,
"author_profile": "https://wordpress.stackexchange.com/users/8591",
"pm_score": 4,
"selected": false,
"text": "<p>If you use WordPress' sideload feature, you can do this more easily (and have WordPress handle all of the sanitization for you).</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n// example:\n// $file = 'http://www.example.com/image.png';\n// $description = 'some description';\n\nfunction my_upload_image( $file, $description ) {\n $file_array = [ 'name' => wp_basename( $file ), 'tmp_name' => download_url( $file ) ];\n\n // If error storing temporarily, return the error.\n if ( is_wp_error( $file_array['tmp_name'] ) ) {\n return $file_array['tmp_name'];\n }\n\n // Do the validation and storage stuff.\n $id = media_handle_sideload( $file_array, 0, $desc );\n\n // If error storing permanently, unlink.\n if ( is_wp_error( $id ) ) {\n @unlink( $file_array['tmp_name'] );\n return $id;\n }\n\n return true;\n}\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113564/"
]
| I am trying to programmatically add multiple images to media library, I uploaded the images to `wp-content/uploads`, now I try to use `wp_insert_attachement`.
Here's the code, however it's not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.
```
$filename_array = array(
'article1.jpg',
'article2.jpg',
);
// The ID of the post this attachment is for.
$parent_post_id = 0;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach ($filename_array as $filename) {
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
``` | ```
$image_url = 'adress img';
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
``` |
256,833 | <p>What is the benefit of using (advantage/disadvantage) </p>
<pre><code>Organize my uploads into month- and year-based folders
</code></pre>
<p>option? Why would I want to organize my folder structure like this ? Is there SEO advantages ?</p>
<p>Thank you</p>
| [
{
"answer_id": 256835,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>OMG, is there nothing else in the world except for SEO this days?</p>\n\n<p>Each OS has limitations and/or performance degradation on the number of files that are in a directory. used to be a limit of 32k files on linux, but this might have changed so don't trust me on exact numbers here, but think how long will it take you to just show a list of 30k files in your favorite FTP software, and how hard it will be to find anything there.</p>\n\n<p>PROs? so small it is not worth mentioning, but if you insist, you might save some bytes in the OS's directory/files related cache. And obviously some bytes saved in disk storage.</p>\n"
},
{
"answer_id": 256836,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>This is one of the many optional features in WordPress.There is no real benefit in using any of these 2 structures, but here is some details for you:</p>\n\n<p><strong>Organization:</strong></p>\n\n<p>When you are building a website which will have a lot of uploads, it is always a good option to go for the year / month structure. You might end up with 100,000 uploads in a single folder if you don't. </p>\n\n<p>As you can imagine, sorting, reading and listing these files will get a long time. There was a time when old file systems used to support limited files in a single folder ( They still do now, but it's way more than before), so you had to make more folders to be able to save the images. </p>\n\n<p>A website with 50K images and 5 thumbnail sizes will end up having 300k images in a single folder!</p>\n\n<p><strong>SEO benefits</strong></p>\n\n<p>There is no actual benefit of having a year / month structure on your files when it comes to SEO. Search engines have other tools to understand your contents, such as <a href=\"http://schema.org/\" rel=\"nofollow noreferrer\">Structured data</a> or HTML5 structure, which let's the search engine understand different parts of a page without using a MicroData structure.</p>\n\n<p><strong>Custom templates - Security</strong></p>\n\n<p>Some users (such as me) prefer to have their website deeply customized, including default folder names. I myself have changed the name all <code>wp-content</code>, <code>wp-admin</code>, <code>uploads</code> and <code>wp-includes</code> folder. Some directly, some through rewriting. </p>\n\n<p>So the first moment a visitor visits the website, it's not easy to understand whether this website is powered by WordPress or not. It also makes it a bit more difficult for a newbie hacker to determine the CMS of the website. </p>\n\n<p>However, with the year / month structure turned to ON, it needs one second to realize that this website is using WordPress to power up.</p>\n\n<p>Although there are several ways to go around this, but still, some do prefer it.</p>\n\n<p>There can be many other things added to this list, their all optional, such as the above list. </p>\n\n<p>I hope this helps you decide what to choose about this.</p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112778/"
]
| What is the benefit of using (advantage/disadvantage)
```
Organize my uploads into month- and year-based folders
```
option? Why would I want to organize my folder structure like this ? Is there SEO advantages ?
Thank you | This is one of the many optional features in WordPress.There is no real benefit in using any of these 2 structures, but here is some details for you:
**Organization:**
When you are building a website which will have a lot of uploads, it is always a good option to go for the year / month structure. You might end up with 100,000 uploads in a single folder if you don't.
As you can imagine, sorting, reading and listing these files will get a long time. There was a time when old file systems used to support limited files in a single folder ( They still do now, but it's way more than before), so you had to make more folders to be able to save the images.
A website with 50K images and 5 thumbnail sizes will end up having 300k images in a single folder!
**SEO benefits**
There is no actual benefit of having a year / month structure on your files when it comes to SEO. Search engines have other tools to understand your contents, such as [Structured data](http://schema.org/) or HTML5 structure, which let's the search engine understand different parts of a page without using a MicroData structure.
**Custom templates - Security**
Some users (such as me) prefer to have their website deeply customized, including default folder names. I myself have changed the name all `wp-content`, `wp-admin`, `uploads` and `wp-includes` folder. Some directly, some through rewriting.
So the first moment a visitor visits the website, it's not easy to understand whether this website is powered by WordPress or not. It also makes it a bit more difficult for a newbie hacker to determine the CMS of the website.
However, with the year / month structure turned to ON, it needs one second to realize that this website is using WordPress to power up.
Although there are several ways to go around this, but still, some do prefer it.
There can be many other things added to this list, their all optional, such as the above list.
I hope this helps you decide what to choose about this. |
256,842 | <p>I added/enqueue a style inside shortcode, it works fine but loaded in footer (before starting the .js files) rather than header. I did the same way like this solution:</p>
<p><a href="https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present">Enqueue Scripts / Styles when shortcode is present</a></p>
<p>Is it normal in WP or how can I load style in header ?</p>
<p>Sample Code Here:</p>
<pre><code>class Cbwsppb_Related {
public function __construct()
{
add_shortcode('cbwsppb_related', array($this, 'shortcode_func'));
}
public function shortcode_func($atts, $content = null)
{
$atts = shortcode_atts( array(
'style' => '',
'display_style' => '',
'show' => '',
'orderby' => ''
), $atts );
if ($atts['display_style'] === 'carousel') {
wp_enqueue_style('flexslider-style');
}
$show = (!empty($atts['show'])) ? $atts['show'] : 2;
$orderby = (!empty($atts['orderby'])) ? $atts['orderby'] : 'rand';
$output = '';
ob_start();
if ($atts['style'] === 'custom') {
$output .= woocommerce_get_template( 'single-product/related.php', array(
'posts_per_page' => $show,
'orderby' => $orderby,
)
);
} else {
$output .= woocommerce_get_template( 'single-product/related.php');
}
$output .= ob_get_clean();
return $output;
}
}
</code></pre>
| [
{
"answer_id": 256845,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>Why it is added in the footer:</h1>\n<p>This is the expected behaviour.</p>\n<p>Since you have enqueued the style <em><strong>within your Shortcode hook function</strong></em>, by the time it executes, WordPress is already done generating the <code><head></code> section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.</p>\n<p>So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.</p>\n<h1>How to add it in the header:</h1>\n<p>If you want to output it in <code><head></code> section, you must enqueue it using:</p>\n<pre><code>function enqueue_your_styles() {\n // the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function \n wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );\n</code></pre>\n<blockquote>\n<p>Note: this will add the style even if you don't have the shortcode in the page.</p>\n<p>Note-2: <a href=\"https://wordpress.stackexchange.com/a/165759/110572\">One of the answers in the question you've mentioned</a> already have a detailed explanation on alternatives and pros & cons.</p>\n</blockquote>\n"
},
{
"answer_id": 256847,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 0,
"selected": false,
"text": "<p>You should try this :</p>\n\n<pre><code>function prefix_add_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_header', 'prefix_add_styles' );\n</code></pre>\n"
},
{
"answer_id": 256849,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>Try below code. Refer from <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a>.</p>\n\n<pre><code> function my_shortcode_style(){\n wp_enqueue_style( 'my_css', plugin_dir_url( __FILE__ ).'style.css', array( '' ), false, 'all' );\n }\n add_action('wp_enqueue_scripts', 'my_shortcode_style');\n</code></pre>\n\n<p>Note: For your plugin directory path use <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_url/\" rel=\"nofollow noreferrer\">plugin_dir_url()</a> and for current theme path use <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\">get_template_directory_uri()</a></p>\n"
},
{
"answer_id": 256920,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>You <em>can</em> pre-check for the presence of the shortcode in the post content and enqueue the script in the header if it is found. </p>\n\n<p>However, you must also fallback to adding it in the footer because the shortcode <em>may</em> be run from elsewhere (eg. in a widget, a template or programmatically.)</p>\n\n<pre><code>public function __construct() {\n add_shortcode('cbwsppb', array($this => 'shortcode_func'));\n add_action('wp', array($this => 'shortcode_check'));\n}\n\npublic function shortcode_check() {\n if (is_single() && (is_product()) {\n global $post; $content = $post->post_content;\n\n // global $wpdb;\n // $query = \"SELECT 'post_content' FROM \"'.$wpdb->prefix.'\"posts WHERE ID = '\".$post->ID.\"'\";\n // $content = $wpdb->get_var($query);\n\n // quick and dirty check for shortcode in post content\n if ( (stristr($content,'[cbwsppb')) \n && (stristr($content,'display_style')) \n && (stristr($content,'carousel')) ) {\n add_action('wp_enqueue_scripts', array($this,'enqueue_styles'));\n }\n }\n}\n\npublic function enqueue_styles() {\n wp_enqueue_style('flexslider-style');\n}\n\npublic function shortcode_func($atts, $content = null) {\n\n // ... $atts = shortcode_atts etc ...\n\n // change this to:\n if ( ($atts['display_style'] === 'carousel')\n && (!wp_style_is('flexslider-style','enqueued')) ) {\n wp_enqueue_style('flexslider-style');\n }\n\n // ... the rest of the shortcode function ...\n}\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256842",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113570/"
]
| I added/enqueue a style inside shortcode, it works fine but loaded in footer (before starting the .js files) rather than header. I did the same way like this solution:
[Enqueue Scripts / Styles when shortcode is present](https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present)
Is it normal in WP or how can I load style in header ?
Sample Code Here:
```
class Cbwsppb_Related {
public function __construct()
{
add_shortcode('cbwsppb_related', array($this, 'shortcode_func'));
}
public function shortcode_func($atts, $content = null)
{
$atts = shortcode_atts( array(
'style' => '',
'display_style' => '',
'show' => '',
'orderby' => ''
), $atts );
if ($atts['display_style'] === 'carousel') {
wp_enqueue_style('flexslider-style');
}
$show = (!empty($atts['show'])) ? $atts['show'] : 2;
$orderby = (!empty($atts['orderby'])) ? $atts['orderby'] : 'rand';
$output = '';
ob_start();
if ($atts['style'] === 'custom') {
$output .= woocommerce_get_template( 'single-product/related.php', array(
'posts_per_page' => $show,
'orderby' => $orderby,
)
);
} else {
$output .= woocommerce_get_template( 'single-product/related.php');
}
$output .= ob_get_clean();
return $output;
}
}
``` | Why it is added in the footer:
==============================
This is the expected behaviour.
Since you have enqueued the style ***within your Shortcode hook function***, by the time it executes, WordPress is already done generating the `<head>` section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.
So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.
How to add it in the header:
============================
If you want to output it in `<head>` section, you must enqueue it using:
```
function enqueue_your_styles() {
// the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function
wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );
```
>
> Note: this will add the style even if you don't have the shortcode in the page.
>
>
> Note-2: [One of the answers in the question you've mentioned](https://wordpress.stackexchange.com/a/165759/110572) already have a detailed explanation on alternatives and pros & cons.
>
>
> |
256,858 | <p>I'm using the following to show a menu</p>
<pre><code>if ( has_nav_menu( 'topheader' ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
) );
}
</code></pre>
<p>If there are no links in the menu, nothing shows in the front-end. Is it possible to display a link to add a menu? Which takes the user to the menu location in dashboard.</p>
| [
{
"answer_id": 256845,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>Why it is added in the footer:</h1>\n<p>This is the expected behaviour.</p>\n<p>Since you have enqueued the style <em><strong>within your Shortcode hook function</strong></em>, by the time it executes, WordPress is already done generating the <code><head></code> section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.</p>\n<p>So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.</p>\n<h1>How to add it in the header:</h1>\n<p>If you want to output it in <code><head></code> section, you must enqueue it using:</p>\n<pre><code>function enqueue_your_styles() {\n // the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function \n wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );\n</code></pre>\n<blockquote>\n<p>Note: this will add the style even if you don't have the shortcode in the page.</p>\n<p>Note-2: <a href=\"https://wordpress.stackexchange.com/a/165759/110572\">One of the answers in the question you've mentioned</a> already have a detailed explanation on alternatives and pros & cons.</p>\n</blockquote>\n"
},
{
"answer_id": 256847,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 0,
"selected": false,
"text": "<p>You should try this :</p>\n\n<pre><code>function prefix_add_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_header', 'prefix_add_styles' );\n</code></pre>\n"
},
{
"answer_id": 256849,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>Try below code. Refer from <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style</a>.</p>\n\n<pre><code> function my_shortcode_style(){\n wp_enqueue_style( 'my_css', plugin_dir_url( __FILE__ ).'style.css', array( '' ), false, 'all' );\n }\n add_action('wp_enqueue_scripts', 'my_shortcode_style');\n</code></pre>\n\n<p>Note: For your plugin directory path use <a href=\"https://developer.wordpress.org/reference/functions/plugin_dir_url/\" rel=\"nofollow noreferrer\">plugin_dir_url()</a> and for current theme path use <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\">get_template_directory_uri()</a></p>\n"
},
{
"answer_id": 256920,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>You <em>can</em> pre-check for the presence of the shortcode in the post content and enqueue the script in the header if it is found. </p>\n\n<p>However, you must also fallback to adding it in the footer because the shortcode <em>may</em> be run from elsewhere (eg. in a widget, a template or programmatically.)</p>\n\n<pre><code>public function __construct() {\n add_shortcode('cbwsppb', array($this => 'shortcode_func'));\n add_action('wp', array($this => 'shortcode_check'));\n}\n\npublic function shortcode_check() {\n if (is_single() && (is_product()) {\n global $post; $content = $post->post_content;\n\n // global $wpdb;\n // $query = \"SELECT 'post_content' FROM \"'.$wpdb->prefix.'\"posts WHERE ID = '\".$post->ID.\"'\";\n // $content = $wpdb->get_var($query);\n\n // quick and dirty check for shortcode in post content\n if ( (stristr($content,'[cbwsppb')) \n && (stristr($content,'display_style')) \n && (stristr($content,'carousel')) ) {\n add_action('wp_enqueue_scripts', array($this,'enqueue_styles'));\n }\n }\n}\n\npublic function enqueue_styles() {\n wp_enqueue_style('flexslider-style');\n}\n\npublic function shortcode_func($atts, $content = null) {\n\n // ... $atts = shortcode_atts etc ...\n\n // change this to:\n if ( ($atts['display_style'] === 'carousel')\n && (!wp_style_is('flexslider-style','enqueued')) ) {\n wp_enqueue_style('flexslider-style');\n }\n\n // ... the rest of the shortcode function ...\n}\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111086/"
]
| I'm using the following to show a menu
```
if ( has_nav_menu( 'topheader' ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
) );
}
```
If there are no links in the menu, nothing shows in the front-end. Is it possible to display a link to add a menu? Which takes the user to the menu location in dashboard. | Why it is added in the footer:
==============================
This is the expected behaviour.
Since you have enqueued the style ***within your Shortcode hook function***, by the time it executes, WordPress is already done generating the `<head>` section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.
So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.
How to add it in the header:
============================
If you want to output it in `<head>` section, you must enqueue it using:
```
function enqueue_your_styles() {
// the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function
wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );
```
>
> Note: this will add the style even if you don't have the shortcode in the page.
>
>
> Note-2: [One of the answers in the question you've mentioned](https://wordpress.stackexchange.com/a/165759/110572) already have a detailed explanation on alternatives and pros & cons.
>
>
> |
256,859 | <p>I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...</p>
<pre><code>$the_query = new WP_Query( array(
'post_type' => 'teacher',
'tax_query' => array(
array(
'taxonomy' => 'ALL CUSTOM TAXONOMIES',
'field' => 'id',
'terms' => 'ALL TERMS'
)
)
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count;
</code></pre>
| [
{
"answer_id": 256865,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>There is the built-in function to count the posts – <code>wp_count_posts()</code>. You can use it to count any post type and any post status:</p>\n\n<pre><code>$published = wp_count_posts('teacher')->publish;\n$future = wp_count_posts('page')->future;\n</code></pre>\n\n<p>For more see <a href=\"https://developer.wordpress.org/reference/functions/wp_count_posts/\" rel=\"nofollow noreferrer\">wp_count_posts()</a> in the Code Reference.</p>\n"
},
{
"answer_id": 256893,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>If the taxonomies in question are used ONLY in the post_type in question, then the following simple function will do what you need:</p>\n\n<pre><code>function\ncount_term_use ($post_type)\n{\n $args = array (\n 'taxonomy' => get_object_taxonomies ($post_type, 'names'),\n ) ;\n foreach (get_terms ($args) as $term) {\n echo \"$term->name - $term->count\\n\" ;\n }\n\n return ;\n}\n</code></pre>\n\n<p>However, if a taxonomy is shared by multiple post_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code.</p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
]
| I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...
```
$the_query = new WP_Query( array(
'post_type' => 'teacher',
'tax_query' => array(
array(
'taxonomy' => 'ALL CUSTOM TAXONOMIES',
'field' => 'id',
'terms' => 'ALL TERMS'
)
)
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count;
``` | If the taxonomies in question are used ONLY in the post\_type in question, then the following simple function will do what you need:
```
function
count_term_use ($post_type)
{
$args = array (
'taxonomy' => get_object_taxonomies ($post_type, 'names'),
) ;
foreach (get_terms ($args) as $term) {
echo "$term->name - $term->count\n" ;
}
return ;
}
```
However, if a taxonomy is shared by multiple post\_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code. |
256,864 | <p>I'm trying to eliminate "mixed content" on my website and have done so with every area of the site except for one.</p>
<p>Any image uploaded via the Theme Customizer is not protocol relative nor https, all images uploaded via the customizer come up "http://". </p>
<p>The Customizer uses the Media Gallery uploader but doesn't seem to act in the same manner. If I upload an image to the media gallery (no customizer), place it into a page, WP knows whether or not to switch between http and https, although, when the same is attempted via the theme customizer function:</p>
<pre><code>$wp_customize->add_setting('slide_img_upload_one');
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'slide_img_upload_one', array(
'label' => __('Upload first image:', 'example_theme'),
'section' => 'carousel_slide_section',
'settings' => 'slide_img_upload_one',
'description' => 'Upload your first slider image here.'
)));
</code></pre>
<p>I can not get the <code>WP_Customize_Image_Control();</code> to output either "https" or a (best case scenario) protocol relative <code>//</code> url to the image for SSL compliance.</p>
<p>Some things to note. I'm not going to force SSL on my website so in Settings -> General; I'm not changing the url away from the http protocol.</p>
<p>I am also not looking for a way to use .htaccess to force this action. </p>
<p>Bottom line, there MUST be a way for images uploaded via the theme customizer to be protocol relative, I need some help figuring this one out though. I am currently running WP 4.6 (yes I know I'm a little behind).</p>
<p>Hopefully someone else has encountered this as hours of R&D have proved useless in trying to address something as specific as WordPress theme customizer func's.</p>
<p>Thanks in advance for any help, ideas, brainstorming... all ideas are welcome!</p>
<p>I am calling in the customizer function on the page using:</p>
<pre><code><a href="<?php echo esc_url(get_theme_mod('slide_one_link')); ?>"><img src="<?php echo esc_url( get_theme_mod( 'slide_img_upload_one' ) ); ?>" alt="<?php echo get_theme_mod( 'slide_title_1' ); ?>" /></a>
</code></pre>
<p>FYI: I have tried the solution here to no avail: <a href="https://wordpress.stackexchange.com/questions/79958/how-to-make-wordpress-use-protocol-indepentent-upload-files">Failed Attempt</a></p>
| [
{
"answer_id": 256865,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>There is the built-in function to count the posts – <code>wp_count_posts()</code>. You can use it to count any post type and any post status:</p>\n\n<pre><code>$published = wp_count_posts('teacher')->publish;\n$future = wp_count_posts('page')->future;\n</code></pre>\n\n<p>For more see <a href=\"https://developer.wordpress.org/reference/functions/wp_count_posts/\" rel=\"nofollow noreferrer\">wp_count_posts()</a> in the Code Reference.</p>\n"
},
{
"answer_id": 256893,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>If the taxonomies in question are used ONLY in the post_type in question, then the following simple function will do what you need:</p>\n\n<pre><code>function\ncount_term_use ($post_type)\n{\n $args = array (\n 'taxonomy' => get_object_taxonomies ($post_type, 'names'),\n ) ;\n foreach (get_terms ($args) as $term) {\n echo \"$term->name - $term->count\\n\" ;\n }\n\n return ;\n}\n</code></pre>\n\n<p>However, if a taxonomy is shared by multiple post_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code.</p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86752/"
]
| I'm trying to eliminate "mixed content" on my website and have done so with every area of the site except for one.
Any image uploaded via the Theme Customizer is not protocol relative nor https, all images uploaded via the customizer come up "http://".
The Customizer uses the Media Gallery uploader but doesn't seem to act in the same manner. If I upload an image to the media gallery (no customizer), place it into a page, WP knows whether or not to switch between http and https, although, when the same is attempted via the theme customizer function:
```
$wp_customize->add_setting('slide_img_upload_one');
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'slide_img_upload_one', array(
'label' => __('Upload first image:', 'example_theme'),
'section' => 'carousel_slide_section',
'settings' => 'slide_img_upload_one',
'description' => 'Upload your first slider image here.'
)));
```
I can not get the `WP_Customize_Image_Control();` to output either "https" or a (best case scenario) protocol relative `//` url to the image for SSL compliance.
Some things to note. I'm not going to force SSL on my website so in Settings -> General; I'm not changing the url away from the http protocol.
I am also not looking for a way to use .htaccess to force this action.
Bottom line, there MUST be a way for images uploaded via the theme customizer to be protocol relative, I need some help figuring this one out though. I am currently running WP 4.6 (yes I know I'm a little behind).
Hopefully someone else has encountered this as hours of R&D have proved useless in trying to address something as specific as WordPress theme customizer func's.
Thanks in advance for any help, ideas, brainstorming... all ideas are welcome!
I am calling in the customizer function on the page using:
```
<a href="<?php echo esc_url(get_theme_mod('slide_one_link')); ?>"><img src="<?php echo esc_url( get_theme_mod( 'slide_img_upload_one' ) ); ?>" alt="<?php echo get_theme_mod( 'slide_title_1' ); ?>" /></a>
```
FYI: I have tried the solution here to no avail: [Failed Attempt](https://wordpress.stackexchange.com/questions/79958/how-to-make-wordpress-use-protocol-indepentent-upload-files) | If the taxonomies in question are used ONLY in the post\_type in question, then the following simple function will do what you need:
```
function
count_term_use ($post_type)
{
$args = array (
'taxonomy' => get_object_taxonomies ($post_type, 'names'),
) ;
foreach (get_terms ($args) as $term) {
echo "$term->name - $term->count\n" ;
}
return ;
}
```
However, if a taxonomy is shared by multiple post\_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code. |
256,868 | <p>I'm attempting to add my logo to the middle of my navbar, and while looking at the nav walker class I couldn't figure what the best way to do this would be.</p>
<p>So my question is essentially how do I do that. the Walker_Nav_Menu() method start_el() seems to build only one li so where is it iterating over all of them and writing them to file. </p>
| [
{
"answer_id": 256882,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to achieve the desired functionality, is to add a new menu item for the logo, by going to the <strong>Appearance</strong> > <strong>Menus</strong>, and set the class of the menu item to <em>logo</em>.</p>\n\n<p>To enable custom CSS class in the menu, click the <strong>Screen Options</strong> then check the <strong>CSS Classes</strong> checkbox.</p>\n\n<p>Let's assume you have a predetermined number of <code>li</code> items of 5.</p>\n\n<pre><code><ul>\n <li class=\"logo\">LOGO</li>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 4</li>\n <li>Item 5</li>\n</ul>\n</code></pre>\n\n<p>Then set the main <code>ul</code> element css display attribute to <code>flex</code>:</p>\n\n<pre><code>ul {\n display: flex\n}\n</code></pre>\n\n<p>And the <code>li</code> order number as follows:</p>\n\n<pre><code>ul li { order: 4; } \nul li:nth-of-type(2) { order: 1; } /* For Item 1 */\nul li:nth-of-type(3) { order: 2; } /* For Item 2 */\n</code></pre>\n\n<p>Then for the <em>logo</em> class:</p>\n\n<pre><code>ul li.logo {\n order: 3;\n}\n</code></pre>\n\n<p>You can learn for about the <strong>order</strong> property of the <a href=\"https://css-tricks.com/almanac/properties/o/order/\" rel=\"nofollow noreferrer\">Flexible Box Layout</a></p>\n"
},
{
"answer_id": 256917,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p>You need to make your own walker menu (i am guessing you already know that), and the best way i think is overriding the function that <code>ends</code> each menu item which is <code>end_el</code> :</p>\n\n<pre><code>class logo_in_middle_Menu_Walker extends Walker_Nav_Menu {\n\n public $menu_location = 'primary';\n\n function __construct($menu_location_var) {\n // parent class doesnt have a constructor so no parent::__construct();\n $this->menu_location = $menu_location_var;\n }\n\n public function end_el(&$output, $item, $depth = 0, $args = array()) {\n $locations = get_nav_menu_locations(); //get all menu locations\n $menu = wp_get_nav_menu_object($locations[$this->menu_location]); //one menu for one location so lets get the menu of this location\n $menu_items = wp_get_nav_menu_items($menu->term_id);\n\n $top_lvl_menu_items_count = 0; //we need this to work with a menu with children too so we dont use simply $menu->count here\n foreach ($menu_items as $menu_item) {\n if ($menu_item->menu_item_parent == \"0\") {\n $top_lvl_menu_items_count++;\n }\n }\n\n $total_menu_items = $top_lvl_menu_items_count;\n\n $item_position = $item->menu_order;\n\n $position_to_have_the_logo = ceil($total_menu_items / 2);\n\n if ($item_position == $position_to_have_the_logo && $item->menu_item_parent == \"0\") { //make sure we output for top level only\n $output .= \"</li>\\n<img src='PATH_TO_YOUR_LOGO' alt='' />\"; //here we add the logo\n } else {\n $output .= \"</li>\\n\";\n }\n }\n}\n</code></pre>\n\n<p>i am assuming that if its a menu with an uneven number of item say 5 the logo will be after the third element, also that this is only for top elements only.</p>\n\n<p>you have to use it like this in the menu location:</p>\n\n<pre><code><?php\n wp_nav_menu(array(\n 'theme_location' => 'footer',\n \"walker\" => new logo_in_middle_Menu_Walker('footer'),\n ));\n?>\n</code></pre>\n\n<p>you have to supply the name of the theme location.</p>\n\n<p>Here with 4 items:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XG6wn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XG6wn.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here with 5:</p>\n\n<p><a href=\"https://i.stack.imgur.com/KgMir.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KgMir.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 377219,
"author": "Logic Design",
"author_id": 196690,
"author_profile": "https://wordpress.stackexchange.com/users/196690",
"pm_score": 1,
"selected": false,
"text": "<p>Modified David Lees nav walker class as for some reason it wouldn't quite work for me with submenu links. Unverified, but believe this was due to the menu items not having tidy/sequential menu_order values.</p>\n<pre><code><?php \n\nclass logo_in_middle_Menu_Walker extends Walker_Nav_Menu {\n\n public $menu_location = 'primary';\n\n function __construct($menu_location_var) {\n $this->menu_location = $menu_location_var;\n }\n\n public function end_el(&$output, $item, $depth = 0, $args = array()) \n {\n $locations = get_nav_menu_locations();\n $menu = wp_get_nav_menu_object($locations[$this->menu_location]);\n $menu_items = wp_get_nav_menu_items($menu->term_id);\n\n $top_level_items = [];\n foreach ( $menu_items as $menu_item ) {\n if ( $menu_item->menu_item_parent == 0 ) {\n $top_level_items[] = $menu_item;\n }\n }\n\n $logo_position = ceil(count($top_level_items) / 2);\n\n if ( $item->menu_item_parent == 0 ) {\n $current_position = 0;\n foreach ( $top_level_items as $index => $top_level_item ) {\n if ( $top_level_item->ID == $item->ID ) {\n $current_position = $index + 1;\n }\n }\n \n if ( $current_position == $logo_position ) {\n $output .= '</li>' . "\\n";\n $output .= '<li class="logo">' . "\\n";\n $output .= '<img src="PATH_TO_YOUR_LOGO" alt="LOGO ALT" />' . "\\n";\n }\n }\n \n $output .= "</li>\\n";\n }\n}\n</code></pre>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108441/"
]
| I'm attempting to add my logo to the middle of my navbar, and while looking at the nav walker class I couldn't figure what the best way to do this would be.
So my question is essentially how do I do that. the Walker\_Nav\_Menu() method start\_el() seems to build only one li so where is it iterating over all of them and writing them to file. | You need to make your own walker menu (i am guessing you already know that), and the best way i think is overriding the function that `ends` each menu item which is `end_el` :
```
class logo_in_middle_Menu_Walker extends Walker_Nav_Menu {
public $menu_location = 'primary';
function __construct($menu_location_var) {
// parent class doesnt have a constructor so no parent::__construct();
$this->menu_location = $menu_location_var;
}
public function end_el(&$output, $item, $depth = 0, $args = array()) {
$locations = get_nav_menu_locations(); //get all menu locations
$menu = wp_get_nav_menu_object($locations[$this->menu_location]); //one menu for one location so lets get the menu of this location
$menu_items = wp_get_nav_menu_items($menu->term_id);
$top_lvl_menu_items_count = 0; //we need this to work with a menu with children too so we dont use simply $menu->count here
foreach ($menu_items as $menu_item) {
if ($menu_item->menu_item_parent == "0") {
$top_lvl_menu_items_count++;
}
}
$total_menu_items = $top_lvl_menu_items_count;
$item_position = $item->menu_order;
$position_to_have_the_logo = ceil($total_menu_items / 2);
if ($item_position == $position_to_have_the_logo && $item->menu_item_parent == "0") { //make sure we output for top level only
$output .= "</li>\n<img src='PATH_TO_YOUR_LOGO' alt='' />"; //here we add the logo
} else {
$output .= "</li>\n";
}
}
}
```
i am assuming that if its a menu with an uneven number of item say 5 the logo will be after the third element, also that this is only for top elements only.
you have to use it like this in the menu location:
```
<?php
wp_nav_menu(array(
'theme_location' => 'footer',
"walker" => new logo_in_middle_Menu_Walker('footer'),
));
?>
```
you have to supply the name of the theme location.
Here with 4 items:
[](https://i.stack.imgur.com/XG6wn.png)
Here with 5:
[](https://i.stack.imgur.com/KgMir.png) |
256,896 | <ol>
<li>I created a php class on a separate file</li>
<li>I included the file in functions.php</li>
<li>I initialized the class</li>
</ol>
<p>The class among many other things has one functions that does this:</p>
<pre><code>$data = array(
'time' => date('Y-m-d H:i:s'),
'offset' => 0,
);
$format = array(
'%s',
'%d'
);
$wpdb->insert('my_custom_table',$data,$format);
</code></pre>
<p>One page load the class runs, and for some reason I get 2 entries in the database instead of one. The data is correct, but I don't know why I have 2 entries if I only inserted once.</p>
<p>In my class $wpdb->insert only runs once. I can test that buy echoing anything right next to it.</p>
<p>troubleshooting:</p>
<p>So I removed $wpdb->insert outside the class and added directly to functions.php. I noticed that the $wpdb->insert was running 2 or more times.</p>
<p>What's causing it to run multiple times?</p>
<p>No, I don't have a loop.
Yes, I know I should not run it in functions.php, but it' for testing only.</p>
<p>I have found similar questions, but no good answer.</p>
| [
{
"answer_id": 256903,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>It's hard to say why without seeing more of your code. So if you're interested in knowing why, then I'd encourage you to share more of your code.</p>\n\n<p>If you're only looking for a solution, then something like the following will probably work. (I say probably because I don't know because I don't have your code.) What we want to do is make sure that the code to insert the table is executed once and only once. Because we're inserting the table on the <code>init</code> hook, the <code>register()</code> method will only fire once because <code>init</code> only fires once. So the conditional check is really unnecessary, but now we know for extra sure that the table will only be added once.</p>\n\n<hr>\n\n<p>functions.php</p>\n\n<pre><code>require_once( PATH_TO . '/class-wpse106269.php' );\nadd_action( 'init', [ wpse106269::getInstance(), 'register' ] );\n</code></pre>\n\n<p>class-wpse106269.php</p>\n\n<pre><code><?php\nclass wpse106269 {\n private static $instance;\n protected $table_already_inserted;\n protected function __construct() {}\n protected function __clone() {}\n protected function __wakeup() {}\n\n public static function getInstance() {\n if( ! isset( self::$instance ) ) {\n self::$instance = new self;\n }\n return self::$instance;\n }\n\n public function register() {\n if( ! $table_already_inserted ) {\n $this->insert_table();\n $this->table_already_inserted = true;\n }\n }\n\n protected function insert_table() {\n //* Insert table here\n }\n</code></pre>\n\n<hr>\n\n<p>Add:</p>\n\n<p>I placed this in my functions.php with only ACF (free) active. The init hook only runs once. So this is either a problem with ACF (pro) or there's another plugin that's still active that doesn't play nicely with ACF (Pro?).</p>\n\n<pre><code>//* Don't access this file directly\ndefined( 'ABSPATH' ) or die();\n\nadd_action( 'init', [ new wpse106269(), 'init' ] );\n\nclass wpse106269{\n protected $n = 1;\n public function init() {\n echo $this->n;\n $this->n = 1 + $this->n;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 256914,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 0,
"selected": false,
"text": "<p>You most likely have a plugin or a theme that is making a separate call to WordPress in the page content, to do something like retrieve CSS or Javascript code. The page loads, and then the stylesheet or JS loads from inside the page in a way that causes WordPress to load a second time.</p>\n\n<p>Alternatively, you have something using the wp-cron system which is causing wp-cron to spawn and thus load WordPress up again in a secondary process (to run whatever the wp-cron action is). This can cause the same effect, especially if you have something using wp-cron on a short timer.</p>\n\n<p>The upshot of it is that WordPress can get loaded for many reasons, and not all of them are to render the page as HTML. So, any time you're \"doing something\" from WordPress loading, then you probably don't want to put it on the init hook, or you want to have a more specific check so that you're not just arbitrarily doing that thing every single time.</p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
]
| 1. I created a php class on a separate file
2. I included the file in functions.php
3. I initialized the class
The class among many other things has one functions that does this:
```
$data = array(
'time' => date('Y-m-d H:i:s'),
'offset' => 0,
);
$format = array(
'%s',
'%d'
);
$wpdb->insert('my_custom_table',$data,$format);
```
One page load the class runs, and for some reason I get 2 entries in the database instead of one. The data is correct, but I don't know why I have 2 entries if I only inserted once.
In my class $wpdb->insert only runs once. I can test that buy echoing anything right next to it.
troubleshooting:
So I removed $wpdb->insert outside the class and added directly to functions.php. I noticed that the $wpdb->insert was running 2 or more times.
What's causing it to run multiple times?
No, I don't have a loop.
Yes, I know I should not run it in functions.php, but it' for testing only.
I have found similar questions, but no good answer. | It's hard to say why without seeing more of your code. So if you're interested in knowing why, then I'd encourage you to share more of your code.
If you're only looking for a solution, then something like the following will probably work. (I say probably because I don't know because I don't have your code.) What we want to do is make sure that the code to insert the table is executed once and only once. Because we're inserting the table on the `init` hook, the `register()` method will only fire once because `init` only fires once. So the conditional check is really unnecessary, but now we know for extra sure that the table will only be added once.
---
functions.php
```
require_once( PATH_TO . '/class-wpse106269.php' );
add_action( 'init', [ wpse106269::getInstance(), 'register' ] );
```
class-wpse106269.php
```
<?php
class wpse106269 {
private static $instance;
protected $table_already_inserted;
protected function __construct() {}
protected function __clone() {}
protected function __wakeup() {}
public static function getInstance() {
if( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
public function register() {
if( ! $table_already_inserted ) {
$this->insert_table();
$this->table_already_inserted = true;
}
}
protected function insert_table() {
//* Insert table here
}
```
---
Add:
I placed this in my functions.php with only ACF (free) active. The init hook only runs once. So this is either a problem with ACF (pro) or there's another plugin that's still active that doesn't play nicely with ACF (Pro?).
```
//* Don't access this file directly
defined( 'ABSPATH' ) or die();
add_action( 'init', [ new wpse106269(), 'init' ] );
class wpse106269{
protected $n = 1;
public function init() {
echo $this->n;
$this->n = 1 + $this->n;
}
}
``` |
256,897 | <p>Wondering if you might have some ideas on this problem. I’m googled for days but can’t figure it out. </p>
<p>Here’s where I’m at:</p>
<p>I have a meta box for the Woocommerce post type ‘products’. Inside the meta box there’s a <code>'type' = > 'select'</code> that I want to populate with a list of all of the available <code>'taxonomy' = > 'product_cat'</code>.</p>
<p>I can get the select box to populate and work with the standard post categories, <code>'taxonomy' = > 'category'</code> using the following code:</p>
<pre><code>function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'category' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
</code></pre>
<p>It all falls apart though when I try to use <code>‘taxonomy' = > ‘product_cat’</code> or any other custom taxonomy I have. </p>
<p>I thought the issue was that I’m trying to access the custom taxonomy before it’s being registered, so I swapped around some declarations/calls in my function.php file (ones which call the CPT, meta boxes, and woocommece) to potentially change the order that things run in but no luck.</p>
<p>BUT, based on the question and answer below, I can now confirm that the function can 'see' and display all terms, across taxonomies. If I exclude the <code>'taxonomy =></code> from the arguments it returns terms from across custom post types and taxonomies. </p>
<p>Ideally the basic function would read:</p>
<pre><code>function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'product_cat' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
</code></pre>
<p>Just wondering if you had any general thoughts? I know it’s difficult without seeing the whole code base, but I thought it would be worth an ask. </p>
<p>Wordpress Version 4.7.2</p>
<p>Woocommerce Version 2.6.14</p>
<p><strong>UPDATE:</strong></p>
<p>Slowly I'm trying to pinpoint my issue.</p>
<p>It appears that <code>'product_cat'</code> can be accessed after all (good) but it's spitting out an array that's not displaying properly. </p>
<p>This is confusing to me as if I simply use <code>get_terms()</code> without any parameters, or specifying <code>'taxonomy' => 'category'</code> the code above works flawlessly</p>
<p>The other pieces of code that I need to work with this are: </p>
<p><em>The array that I'd like the list of options to dump in to</em></p>
<pre><code> array(
'label'=> 'Collections',
'desc' => 'Select the collection you would like to display',
'id' => $prefix.'collection',
'type' => 'select',
'options' => product_cats()
),
</code></pre>
<p><em>the code which generates the select list (used for other meta fields)</em></p>
<pre><code>// select
case 'select':
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
</code></pre>
<p>I have zero issues with any other meta fields working or displaying, including select lists. </p>
<p>I'd rather no re-write the entire meta box with all of its fields so I'm trying to work with what I have at the moment. </p>
| [
{
"answer_id": 256900,
"author": "Marinus Klasen",
"author_id": 113579,
"author_profile": "https://wordpress.stackexchange.com/users/113579",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably not gonna fix it, but wanted to share: I ran into the same issue today and this was caused by not having any products in my categories. If this is the case for you too, make sure to add <code>'hide_empty' => false</code>.</p>\n\n<p>That said. When you run <code>get_terms()</code> without any arguments. What is the output?</p>\n"
},
{
"answer_id": 256902,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You are maybe running an old version of WordPress (before 4.5).</p>\n\n<p>Before WordPress 4.5.0, the first parameter of get_terms() was a taxonomy or list of taxonomies and since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array (that what you are doing, it should work like that).</p>\n\n<p>You will find all the details about these changes in the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">get_terms() reference page</a>.</p>\n\n<p><strong>UPDATE :</strong> \nSorry, I verify my code, and I use get_categories() not get_terms, and that right get_terms() don't work !</p>\n\n<p>here is a working example to list all my product_cat</p>\n\n<pre><code>$product_categories = get_categories( array(\n 'taxonomy' => 'product_cat',\n 'orderby' => 'name',\n 'pad_counts' => false,\n 'hierarchical' => 1,\n 'hide_empty' => false\n) );\n</code></pre>\n\n<p>Hope it helps !</p>\n"
},
{
"answer_id": 256910,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a fully working example of a meta box that displays a product category select box. The meta box will appear on the product post type.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'wpse256897_add_meta_box' );\nadd_action( 'save_post', 'wpse256897_save' );\n/**\n * Adds the meta box container.\n */\nfunction wpse256897_add_meta_box( $post_type ) {\n // Limit meta box to certain post types.\n $post_types = array( 'product' );\n\n if ( in_array( $post_type, $post_types ) ) {\n add_meta_box(\n 'product_cat_selection',\n __( 'Product Category Selection', 'textdomain' ),\n 'wpse256897_render_meta_box_content',\n $post_type,\n 'advanced',\n 'high'\n );\n }\n}\n\n/**\n * Save the meta when the post is saved.\n *\n * @param int $post_id The ID of the post being saved.\n */\nfunction wpse256897_save( $post_id ) {\n /*\n * We need to verify this came from the our screen and with proper authorization,\n * because save_post can be triggered at other times.\n */\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['myplugin_inner_custom_box_nonce'] ) ) {\n return $post_id;\n }\n\n $nonce = $_POST['myplugin_inner_custom_box_nonce'];\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) ) {\n return $post_id;\n }\n\n /*\n * If this is an autosave, our form has not been submitted,\n * so we don't want to do anything.\n */\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {\n return $post_id;\n }\n\n // Check the user's permissions.\n if ( 'page' == $_POST['post_type'] ) {\n if ( ! current_user_can( 'edit_page', $post_id ) ) {\n return $post_id;\n }\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return $post_id;\n }\n }\n\n /* OK, it's safe for us to save the data now. */\n\n // Sanitize the user input.\n $mydata = sanitize_text_field( $_POST['product_cat_selection'] );\n\n // Update the meta field.\n update_post_meta( $post_id, '_product_cat_selection', $mydata );\n}\n\n/**\n * Render Meta Box content.\n *\n * @param WP_Post $post The post object.\n */\nfunction wpse256897_render_meta_box_content( $post ) {\n // Add an nonce field so we can check for it later.\n wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );\n\n // Use get_post_meta to retrieve an existing value from the database.\n $current_product_cat = get_post_meta( $post->ID, '_product_cat_selection', true );\n\n // Display the form, using the current value.\n $product_cats = wpse256897_product_cats();\n if ( !empty ( $product_cats ) ) {\n echo '<select name=\"product_cat_selection\" id=\"product_cat_selection\">';\n foreach ( $product_cats as $product_cat_id => $product_cat ) { ?>\n <option value=\"<?php echo esc_attr( $product_cat['value'] ); ?>\" <?php if ( isset ( $current_product_cat ) ) selected( $current_product_cat, $product_cat['value'] ); ?>><?php echo esc_html( $product_cat['label'] ); ?></option><?php\n }\n echo '</select>';\n }\n} \n\nfunction wpse256897_product_cats() {\n $options = array();\n $categories = get_terms( array( 'taxonomy' => 'product_cat' ) );\n\n foreach( $categories as $category ) {\n $options[$category->term_id] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n\n return $options;\n}\n</code></pre>\n\n<p>This is not the most elegant example (the naming conventions could be better). It was quickly adapted from the contributed notes on the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">Add Meta Box reference page</a>, but it does demonstrate that <code>wpse256897_product_cats()</code> does get the product categories and that they can be saved and displayed in a select box on the product page within a meta box.</p>\n\n<p>I'd also like to add that it might be worth checking out the <a href=\"https://codex.wordpress.org/Function_Reference/wp_dropdown_categories\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> function. Which, despite its name, works with custom taxonomies too. This would save you from creating your own category dropdown markup.</p>\n\n<p><strong>Update:</strong>\nIt sounds like the structure of the array returned by the <code>product_cats()</code> function is not jiving with your meta box implementation. Notice that in my example above, I used this line to loop over the categories when generating the options for the select element:</p>\n\n<pre><code>foreach ( $product_cats as $product_cat_id => $product_cat ) { ?>\n</code></pre>\n\n<p>This is because <code>$product_cats</code> is an associative array of category ids which each hold another array containing the <code>label</code> and <code>slug</code> for each category id.</p>\n\n<p>It looks like you could possibly use this alternate version of <code>product_cats()</code> which formats the return value $options in a way that is compatible with your metabox code:</p>\n\n<pre><code>function product_cats_alternate() {\n $options = array();\n\n $categories = get_terms( array( 'taxonomy' => 'product_cat' ) );\n foreach( $categories as $category ) {\n $options[] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n return $options;\n}\n</code></pre>\n"
},
{
"answer_id": 256954,
"author": "Kevin Van Lierop",
"author_id": 113596,
"author_profile": "https://wordpress.stackexchange.com/users/113596",
"pm_score": 2,
"selected": true,
"text": "<p>For the life of me I really want to get this working the <em>right way</em>. For the life of me I can't figure the integration out.</p>\n\n<p>Previously I had looked at <a href=\"https://codex.wordpress.org/Function_Reference/wp_dropdown_categories\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax. </p>\n\n<p>For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.</p>\n\n<pre><code>// Wrap all categories in a function\nfunction product_cats() {\n $output = array();\n $categories = get_terms( array(\n 'orderby' => 'name',\n 'pad_counts' => false,\n 'hierarchical' => 1,\n 'hide_empty' => true,\n ) );\n foreach( $categories as $category ) {\n if ($category->taxonomy == 'product_cat' ) {\n $output[$category->slug] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n }\n //return array('options'=>$output);\n return $output;\n}\n</code></pre>\n\n<p>I'll update more as I move along. </p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113596/"
]
| Wondering if you might have some ideas on this problem. I’m googled for days but can’t figure it out.
Here’s where I’m at:
I have a meta box for the Woocommerce post type ‘products’. Inside the meta box there’s a `'type' = > 'select'` that I want to populate with a list of all of the available `'taxonomy' = > 'product_cat'`.
I can get the select box to populate and work with the standard post categories, `'taxonomy' = > 'category'` using the following code:
```
function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'category' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
```
It all falls apart though when I try to use `‘taxonomy' = > ‘product_cat’` or any other custom taxonomy I have.
I thought the issue was that I’m trying to access the custom taxonomy before it’s being registered, so I swapped around some declarations/calls in my function.php file (ones which call the CPT, meta boxes, and woocommece) to potentially change the order that things run in but no luck.
BUT, based on the question and answer below, I can now confirm that the function can 'see' and display all terms, across taxonomies. If I exclude the `'taxonomy =>` from the arguments it returns terms from across custom post types and taxonomies.
Ideally the basic function would read:
```
function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'product_cat' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
```
Just wondering if you had any general thoughts? I know it’s difficult without seeing the whole code base, but I thought it would be worth an ask.
Wordpress Version 4.7.2
Woocommerce Version 2.6.14
**UPDATE:**
Slowly I'm trying to pinpoint my issue.
It appears that `'product_cat'` can be accessed after all (good) but it's spitting out an array that's not displaying properly.
This is confusing to me as if I simply use `get_terms()` without any parameters, or specifying `'taxonomy' => 'category'` the code above works flawlessly
The other pieces of code that I need to work with this are:
*The array that I'd like the list of options to dump in to*
```
array(
'label'=> 'Collections',
'desc' => 'Select the collection you would like to display',
'id' => $prefix.'collection',
'type' => 'select',
'options' => product_cats()
),
```
*the code which generates the select list (used for other meta fields)*
```
// select
case 'select':
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
```
I have zero issues with any other meta fields working or displaying, including select lists.
I'd rather no re-write the entire meta box with all of its fields so I'm trying to work with what I have at the moment. | For the life of me I really want to get this working the *right way*. For the life of me I can't figure the integration out.
Previously I had looked at [`wp_dropdown_categories()`](https://codex.wordpress.org/Function_Reference/wp_dropdown_categories) and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax.
For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.
```
// Wrap all categories in a function
function product_cats() {
$output = array();
$categories = get_terms( array(
'orderby' => 'name',
'pad_counts' => false,
'hierarchical' => 1,
'hide_empty' => true,
) );
foreach( $categories as $category ) {
if ($category->taxonomy == 'product_cat' ) {
$output[$category->slug] = array(
'label' => $category->name,
'value' => $category->slug
);
}
}
//return array('options'=>$output);
return $output;
}
```
I'll update more as I move along. |
256,904 | <p>I migrated my wordpress, and the subscribe2 plugin
<a href="https://wordpress.org/plugins/subscribe2/installation/" rel="nofollow noreferrer">https://wordpress.org/plugins/subscribe2/installation/</a></p>
<p>looks different now. Before it has a text box with a placeholder, and then two buttons under saying subscribe and unsubscribe. The old plugin was version 4.16, and now the new version is 10.21. The way the new version looks like, is there is no input field or buttons. Rather it's just a sentence that says "you may manage your subscription options from your profile". And "profile" is a link.</p>
<p>Does anyone know how to get it to look like the old way?</p>
<p>Thanks</p>
| [
{
"answer_id": 256900,
"author": "Marinus Klasen",
"author_id": 113579,
"author_profile": "https://wordpress.stackexchange.com/users/113579",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably not gonna fix it, but wanted to share: I ran into the same issue today and this was caused by not having any products in my categories. If this is the case for you too, make sure to add <code>'hide_empty' => false</code>.</p>\n\n<p>That said. When you run <code>get_terms()</code> without any arguments. What is the output?</p>\n"
},
{
"answer_id": 256902,
"author": "Benoti",
"author_id": 58141,
"author_profile": "https://wordpress.stackexchange.com/users/58141",
"pm_score": 1,
"selected": false,
"text": "<p>You are maybe running an old version of WordPress (before 4.5).</p>\n\n<p>Before WordPress 4.5.0, the first parameter of get_terms() was a taxonomy or list of taxonomies and since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array (that what you are doing, it should work like that).</p>\n\n<p>You will find all the details about these changes in the <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">get_terms() reference page</a>.</p>\n\n<p><strong>UPDATE :</strong> \nSorry, I verify my code, and I use get_categories() not get_terms, and that right get_terms() don't work !</p>\n\n<p>here is a working example to list all my product_cat</p>\n\n<pre><code>$product_categories = get_categories( array(\n 'taxonomy' => 'product_cat',\n 'orderby' => 'name',\n 'pad_counts' => false,\n 'hierarchical' => 1,\n 'hide_empty' => false\n) );\n</code></pre>\n\n<p>Hope it helps !</p>\n"
},
{
"answer_id": 256910,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a fully working example of a meta box that displays a product category select box. The meta box will appear on the product post type.</p>\n\n<pre><code>add_action( 'add_meta_boxes', 'wpse256897_add_meta_box' );\nadd_action( 'save_post', 'wpse256897_save' );\n/**\n * Adds the meta box container.\n */\nfunction wpse256897_add_meta_box( $post_type ) {\n // Limit meta box to certain post types.\n $post_types = array( 'product' );\n\n if ( in_array( $post_type, $post_types ) ) {\n add_meta_box(\n 'product_cat_selection',\n __( 'Product Category Selection', 'textdomain' ),\n 'wpse256897_render_meta_box_content',\n $post_type,\n 'advanced',\n 'high'\n );\n }\n}\n\n/**\n * Save the meta when the post is saved.\n *\n * @param int $post_id The ID of the post being saved.\n */\nfunction wpse256897_save( $post_id ) {\n /*\n * We need to verify this came from the our screen and with proper authorization,\n * because save_post can be triggered at other times.\n */\n\n // Check if our nonce is set.\n if ( ! isset( $_POST['myplugin_inner_custom_box_nonce'] ) ) {\n return $post_id;\n }\n\n $nonce = $_POST['myplugin_inner_custom_box_nonce'];\n\n // Verify that the nonce is valid.\n if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) ) {\n return $post_id;\n }\n\n /*\n * If this is an autosave, our form has not been submitted,\n * so we don't want to do anything.\n */\n if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {\n return $post_id;\n }\n\n // Check the user's permissions.\n if ( 'page' == $_POST['post_type'] ) {\n if ( ! current_user_can( 'edit_page', $post_id ) ) {\n return $post_id;\n }\n } else {\n if ( ! current_user_can( 'edit_post', $post_id ) ) {\n return $post_id;\n }\n }\n\n /* OK, it's safe for us to save the data now. */\n\n // Sanitize the user input.\n $mydata = sanitize_text_field( $_POST['product_cat_selection'] );\n\n // Update the meta field.\n update_post_meta( $post_id, '_product_cat_selection', $mydata );\n}\n\n/**\n * Render Meta Box content.\n *\n * @param WP_Post $post The post object.\n */\nfunction wpse256897_render_meta_box_content( $post ) {\n // Add an nonce field so we can check for it later.\n wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );\n\n // Use get_post_meta to retrieve an existing value from the database.\n $current_product_cat = get_post_meta( $post->ID, '_product_cat_selection', true );\n\n // Display the form, using the current value.\n $product_cats = wpse256897_product_cats();\n if ( !empty ( $product_cats ) ) {\n echo '<select name=\"product_cat_selection\" id=\"product_cat_selection\">';\n foreach ( $product_cats as $product_cat_id => $product_cat ) { ?>\n <option value=\"<?php echo esc_attr( $product_cat['value'] ); ?>\" <?php if ( isset ( $current_product_cat ) ) selected( $current_product_cat, $product_cat['value'] ); ?>><?php echo esc_html( $product_cat['label'] ); ?></option><?php\n }\n echo '</select>';\n }\n} \n\nfunction wpse256897_product_cats() {\n $options = array();\n $categories = get_terms( array( 'taxonomy' => 'product_cat' ) );\n\n foreach( $categories as $category ) {\n $options[$category->term_id] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n\n return $options;\n}\n</code></pre>\n\n<p>This is not the most elegant example (the naming conventions could be better). It was quickly adapted from the contributed notes on the <a href=\"https://developer.wordpress.org/reference/functions/add_meta_box/\" rel=\"nofollow noreferrer\">Add Meta Box reference page</a>, but it does demonstrate that <code>wpse256897_product_cats()</code> does get the product categories and that they can be saved and displayed in a select box on the product page within a meta box.</p>\n\n<p>I'd also like to add that it might be worth checking out the <a href=\"https://codex.wordpress.org/Function_Reference/wp_dropdown_categories\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> function. Which, despite its name, works with custom taxonomies too. This would save you from creating your own category dropdown markup.</p>\n\n<p><strong>Update:</strong>\nIt sounds like the structure of the array returned by the <code>product_cats()</code> function is not jiving with your meta box implementation. Notice that in my example above, I used this line to loop over the categories when generating the options for the select element:</p>\n\n<pre><code>foreach ( $product_cats as $product_cat_id => $product_cat ) { ?>\n</code></pre>\n\n<p>This is because <code>$product_cats</code> is an associative array of category ids which each hold another array containing the <code>label</code> and <code>slug</code> for each category id.</p>\n\n<p>It looks like you could possibly use this alternate version of <code>product_cats()</code> which formats the return value $options in a way that is compatible with your metabox code:</p>\n\n<pre><code>function product_cats_alternate() {\n $options = array();\n\n $categories = get_terms( array( 'taxonomy' => 'product_cat' ) );\n foreach( $categories as $category ) {\n $options[] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n return $options;\n}\n</code></pre>\n"
},
{
"answer_id": 256954,
"author": "Kevin Van Lierop",
"author_id": 113596,
"author_profile": "https://wordpress.stackexchange.com/users/113596",
"pm_score": 2,
"selected": true,
"text": "<p>For the life of me I really want to get this working the <em>right way</em>. For the life of me I can't figure the integration out.</p>\n\n<p>Previously I had looked at <a href=\"https://codex.wordpress.org/Function_Reference/wp_dropdown_categories\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax. </p>\n\n<p>For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.</p>\n\n<pre><code>// Wrap all categories in a function\nfunction product_cats() {\n $output = array();\n $categories = get_terms( array(\n 'orderby' => 'name',\n 'pad_counts' => false,\n 'hierarchical' => 1,\n 'hide_empty' => true,\n ) );\n foreach( $categories as $category ) {\n if ($category->taxonomy == 'product_cat' ) {\n $output[$category->slug] = array(\n 'label' => $category->name,\n 'value' => $category->slug\n );\n }\n }\n //return array('options'=>$output);\n return $output;\n}\n</code></pre>\n\n<p>I'll update more as I move along. </p>\n"
}
]
| 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113339/"
]
| I migrated my wordpress, and the subscribe2 plugin
<https://wordpress.org/plugins/subscribe2/installation/>
looks different now. Before it has a text box with a placeholder, and then two buttons under saying subscribe and unsubscribe. The old plugin was version 4.16, and now the new version is 10.21. The way the new version looks like, is there is no input field or buttons. Rather it's just a sentence that says "you may manage your subscription options from your profile". And "profile" is a link.
Does anyone know how to get it to look like the old way?
Thanks | For the life of me I really want to get this working the *right way*. For the life of me I can't figure the integration out.
Previously I had looked at [`wp_dropdown_categories()`](https://codex.wordpress.org/Function_Reference/wp_dropdown_categories) and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax.
For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.
```
// Wrap all categories in a function
function product_cats() {
$output = array();
$categories = get_terms( array(
'orderby' => 'name',
'pad_counts' => false,
'hierarchical' => 1,
'hide_empty' => true,
) );
foreach( $categories as $category ) {
if ($category->taxonomy == 'product_cat' ) {
$output[$category->slug] = array(
'label' => $category->name,
'value' => $category->slug
);
}
}
//return array('options'=>$output);
return $output;
}
```
I'll update more as I move along. |
256,930 | <p>I created a page template named custpage.php
I also created a separate css file named style2.css to style the custpage which has html and php code.
The page templates loads fine it shows under the page attributes but the css stylesheet doesn't seem to work.</p>
<p>This is what I did in functions.php</p>
<pre><code>function register_cust_style() {
if ( is_page_template( 'custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
}
add_action( 'wp_enqueue_scripts', 'register_cust_style' );
</code></pre>
<p>The css file is inside vega/style2.css (where vega is name of the template directory).</p>
| [
{
"answer_id": 256936,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<p><code>'vega'</code> - must be unique name (example: 'vega-custpage-css')</p>\n\n<pre><code>wp_enqueue_style( 'vega-custpage-css', get_stylesheet_directory_uri() . '/style2.css' );\n</code></pre>\n\n<p>Style file must be located:</p>\n\n<pre><code>http://site.ru/wp-content/themes/twentyten/style2.css\n</code></pre>\n"
},
{
"answer_id": 256962,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>This will work only if your template is in the root folder, if its in a subdirectory you need to supply that too:</p>\n\n<pre><code>if ( is_page_template( 'template_folder_name/custpage.php' ) ) {\n wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );\n}\n</code></pre>\n"
},
{
"answer_id": 257029,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 0,
"selected": false,
"text": "<p>To help debugging, you really want to know first off if <code>is_page_template</code> is returning true or not... for that you can do something like...</p>\n\n<pre><code>add_action('wp','page_template_check');\n\nfunction page_template_check() {\n if ( is_page_template( 'custpage.php' ) ) {\n echo \"<!-- custpage.php is correct -->\";\n }\n\n $template = get_page_template_slug( get_the_ID() );\n echo \"<!-- Template: '\".$template.\"' -->\";\n}\n</code></pre>\n\n<p>(the second test is from the <a href=\"https://developer.wordpress.org/reference/functions/is_page_template/\" rel=\"nofollow noreferrer\">is_page_template</a> developer codex page.</p>\n\n<p>Then view the page source... if they are different results then adjust, if they are the same then the problem is with the enqueueing after all (you need a unique slug as @TrubinE mentioned.)</p>\n"
}
]
| 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113620/"
]
| I created a page template named custpage.php
I also created a separate css file named style2.css to style the custpage which has html and php code.
The page templates loads fine it shows under the page attributes but the css stylesheet doesn't seem to work.
This is what I did in functions.php
```
function register_cust_style() {
if ( is_page_template( 'custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
}
add_action( 'wp_enqueue_scripts', 'register_cust_style' );
```
The css file is inside vega/style2.css (where vega is name of the template directory). | This will work only if your template is in the root folder, if its in a subdirectory you need to supply that too:
```
if ( is_page_template( 'template_folder_name/custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
``` |
256,967 | <p>My website has a logo and this logo have 2 states (i.e. online and offline ). Each of them has an image that will be uploaded to the media. What I am trying to achieve is that, when hovering on, the state of the logo changes (this can be done quite easy). However, in order to easily keep track of the logo image, I am thinking of allowing the theme to support custom_logo through add_theme_support. This works halfway, meaning I can only control 1 of the image at the moment. Are there any ways I can allow adding 2 different images from the theme customizing (custom logo) and display them? Thanks in advance</p>
| [
{
"answer_id": 256980,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 4,
"selected": true,
"text": "<p>I am assuming that by online and offline you mean active states of the logo. I think there are several options for you to use. The first two options can be used within your theme and then are simply changing the image file within the directory.</p>\n\n<h3>Option One (not using WP):</h3>\n\n<p>You can utilise a simple use of transparancy. Apply a transparent effect to the logo and then on hover, make the opacity full. E.g:</p>\n\n<pre><code>.logo {\n opacity: 0.75;\n}\n\n.logo:hover {\n opacity: 1;\n}\n\n// If you want to use SASS:\n\n.logo {\n opacity: 0.75;\n\n &:hover {\n opacity: 1;\n }\n}\n</code></pre>\n\n<h3>Option Two (not using WP):</h3>\n\n<p>If you need to use imagery instead of an hover effect, then you can try the following (again using classes):</p>\n\n<pre><code>.logo {\n background-image: url('path/to/your-off-image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n width: 200px; // Have to set a width/height in order for the background to appear\n height: 200px;\n}\n\n.logo:hover {\n background-image: url('path/to/your-on-image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n}\n\n// If you want to use SASS:\n\n.logo {\n background-image: url('path/to/your-off-image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n width: 200px; // Have to set a width/height in order for the background to appear\n height: 200px;\n\n &:hover {\n background-image: url('path/to/your-on-image.jpg');\n background-repeat: no-repeat;\n background-size: cover;\n }\n}\n</code></pre>\n\n<h3>Option Three (using the customiser in WP):</h3>\n\n<p><em>Taken from the <a href=\"https://codex.wordpress.org/Theme_Customization_API#Adding_a_New_Setting\" rel=\"noreferrer\">WP Customiser Docs</a></em></p>\n\n<p>With this option you have to register the setting using the following:</p>\n\n<pre><code>function mytheme_customize_register( $wp_customize ) {\n //All our sections, settings, and controls will be added here\n\n $wp_customize->add_section( 'my_site_logo' , array(\n 'title' => __( 'My Site Logo', 'mytheme' ),\n 'priority' => 30,\n ) );\n\n $wp_customize->add_control(\n new WP_Customize_Image_Control(\n $wp_customize,\n 'logo',\n array(\n 'label' => __( 'Upload a logo', 'theme_name' ),\n 'section' => 'my_site_logo',\n 'settings' => 'my_site_logo_id' \n )\n )\n );\n\n}\nadd_action( 'customize_register', 'mytheme_customize_register' );\n</code></pre>\n\n<p>The above code would be added into the functions.php file that should be located within your theme directory. In order retrieve the image you do the following:</p>\n\n<pre><code>get_theme_mod( 'my_site_logo_id' );\n</code></pre>\n\n<p>And then you would have to break with convention of using inline-styling to output the two different options for the logos, on hover.</p>\n\n<p>Please check out the codex to check over the various options you may have in order to achieve what you are after.</p>\n"
},
{
"answer_id": 256983,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 0,
"selected": false,
"text": "<p>you can have only one image as a logo by default but this can be extended to two by another custom control in wp customizer. </p>\n\n<p>another solution is to use a single image with both active and hover states into it. and control the view with css position property like old way of using image icons.</p>\n\n<p>for example you could have an image height of 100px. 50px will contain by default logo and another 50px will contain hover state of logo. then by default show the 0px to 50px height of image and when its active or on hover state change background position to 50px to 100px. the image wrapper height should be 50px with <code>overflow:hidden</code></p>\n"
},
{
"answer_id": 256985,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 4,
"selected": false,
"text": "<p>When you use <code>add_theme_support('custom-logo');</code> the logo uploader that is added to the <code>Site Identity</code> Section will use <code>WP_Customize_Image_Control</code> which doesn't support multiple images, its only for 1.</p>\n\n<p><strong>Simpler solution</strong>:</p>\n\n<p>Add a second control just below the one WordPress one with this code:</p>\n\n<pre><code>function your_theme_customizer_setting($wp_customize) {\n// add a setting \n $wp_customize->add_setting('your_theme_hover_logo');\n// Add a control to upload the hover logo\n $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'your_theme_hover_logo', array(\n 'label' => 'Upload Hover Logo',\n 'section' => 'title_tagline', //this is the section where the custom-logo from WordPress is\n 'settings' => 'your_theme_hover_logo',\n 'priority' => 8 // show it just below the custom-logo\n )));\n}\n\nadd_action('customize_register', 'your_theme_customizer_setting');\n</code></pre>\n\n<p>use it with <code>get_theme_mod( 'your_theme_hover_logo' )</code>.</p>\n\n<p><strong>Complex Solution</strong>:</p>\n\n<p>Create your own custom control that will accept 2 images.</p>\n"
},
{
"answer_id": 256987,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": -1,
"selected": false,
"text": "<p>Advice against bothering with the customizer for this. It is easier to find, override and change a logo with is part of a CSS file than trying to figure out where did you put the option to control it. The amount of effort required to code and test a solution has no justification.\nAdditional advantage is that all the code can be put under GIT and track the logo changes.</p>\n\n<p>(Obviously themes that are being distributed need such an option, but IMHO for a site specific theme it is a useless feature)</p>\n"
}
]
| 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109824/"
]
| My website has a logo and this logo have 2 states (i.e. online and offline ). Each of them has an image that will be uploaded to the media. What I am trying to achieve is that, when hovering on, the state of the logo changes (this can be done quite easy). However, in order to easily keep track of the logo image, I am thinking of allowing the theme to support custom\_logo through add\_theme\_support. This works halfway, meaning I can only control 1 of the image at the moment. Are there any ways I can allow adding 2 different images from the theme customizing (custom logo) and display them? Thanks in advance | I am assuming that by online and offline you mean active states of the logo. I think there are several options for you to use. The first two options can be used within your theme and then are simply changing the image file within the directory.
### Option One (not using WP):
You can utilise a simple use of transparancy. Apply a transparent effect to the logo and then on hover, make the opacity full. E.g:
```
.logo {
opacity: 0.75;
}
.logo:hover {
opacity: 1;
}
// If you want to use SASS:
.logo {
opacity: 0.75;
&:hover {
opacity: 1;
}
}
```
### Option Two (not using WP):
If you need to use imagery instead of an hover effect, then you can try the following (again using classes):
```
.logo {
background-image: url('path/to/your-off-image.jpg');
background-repeat: no-repeat;
background-size: cover;
width: 200px; // Have to set a width/height in order for the background to appear
height: 200px;
}
.logo:hover {
background-image: url('path/to/your-on-image.jpg');
background-repeat: no-repeat;
background-size: cover;
}
// If you want to use SASS:
.logo {
background-image: url('path/to/your-off-image.jpg');
background-repeat: no-repeat;
background-size: cover;
width: 200px; // Have to set a width/height in order for the background to appear
height: 200px;
&:hover {
background-image: url('path/to/your-on-image.jpg');
background-repeat: no-repeat;
background-size: cover;
}
}
```
### Option Three (using the customiser in WP):
*Taken from the [WP Customiser Docs](https://codex.wordpress.org/Theme_Customization_API#Adding_a_New_Setting)*
With this option you have to register the setting using the following:
```
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->add_section( 'my_site_logo' , array(
'title' => __( 'My Site Logo', 'mytheme' ),
'priority' => 30,
) );
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'logo',
array(
'label' => __( 'Upload a logo', 'theme_name' ),
'section' => 'my_site_logo',
'settings' => 'my_site_logo_id'
)
)
);
}
add_action( 'customize_register', 'mytheme_customize_register' );
```
The above code would be added into the functions.php file that should be located within your theme directory. In order retrieve the image you do the following:
```
get_theme_mod( 'my_site_logo_id' );
```
And then you would have to break with convention of using inline-styling to output the two different options for the logos, on hover.
Please check out the codex to check over the various options you may have in order to achieve what you are after. |
256,976 | <p>I'm currently setting up a sidebar menu with multiple menus and sections. Each section with the title (the menu name) and a bunch of links underneath (the menu items) - I printed the items, but how do I print the menu name?</p>
<p>Thanks,</p>
<p>Jacob</p>
| [
{
"answer_id": 256979,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 5,
"selected": true,
"text": "<p>You can access the menu metadata using the <code>wp_get_nav_menu_object</code> function</p>\n\n<p>BY NAME:</p>\n\n<pre><code>$menu = wp_get_nav_menu_object(\"my mainmenu\" );\n</code></pre>\n\n<p>BY SLUG:</p>\n\n<pre><code>$menu = wp_get_nav_menu_object(\"my-mainmenu\" );\n</code></pre>\n\n<p>The return object as follows:</p>\n\n<pre><code> Object (\n term_id => 4\n name => My Menu Name\n slug => my-menu-name\n term_group => 0\n term_taxonomy_id => 4\n taxonomy => nav_menu\n description => \n parent => 0\n count => 6\n )\n</code></pre>\n\n<p>To display the name:</p>\n\n<pre><code>echo $menu->name;\n</code></pre>\n"
},
{
"answer_id": 256981,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": false,
"text": "<p>You can get the name like this, using the menu location, so if the menu is updated or you assign other menu you dont have to update anything here:</p>\n\n<pre><code>$locations = get_nav_menu_locations(); //get all menu locations\n$menu = wp_get_nav_menu_object($locations['name_of_the_menu_location']);//get the menu object\n\necho $menu->name; // name of the menu\n</code></pre>\n\n<p>the <code>'name_of_the_menu_location'</code> is the one you use to output a menu using <code>wp_nav_menu</code></p>\n\n<pre><code><?php\n wp_nav_menu(array(\n 'theme_location' => 'footer'//this value\n ));\n?>\n</code></pre>\n"
},
{
"answer_id": 323653,
"author": "Merhawi Fissehaye",
"author_id": 91327,
"author_profile": "https://wordpress.stackexchange.com/users/91327",
"pm_score": 5,
"selected": false,
"text": "<p>On WordPress version 4.9.0 and above you can use</p>\n\n<pre><code>wp_get_nav_menu_name($location)\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_name/\" rel=\"noreferrer\">wp_nav_menu_name</a> for more</p>\n"
}
]
| 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94333/"
]
| I'm currently setting up a sidebar menu with multiple menus and sections. Each section with the title (the menu name) and a bunch of links underneath (the menu items) - I printed the items, but how do I print the menu name?
Thanks,
Jacob | You can access the menu metadata using the `wp_get_nav_menu_object` function
BY NAME:
```
$menu = wp_get_nav_menu_object("my mainmenu" );
```
BY SLUG:
```
$menu = wp_get_nav_menu_object("my-mainmenu" );
```
The return object as follows:
```
Object (
term_id => 4
name => My Menu Name
slug => my-menu-name
term_group => 0
term_taxonomy_id => 4
taxonomy => nav_menu
description =>
parent => 0
count => 6
)
```
To display the name:
```
echo $menu->name;
``` |
257,024 | <p>The following code gives all posts from the network.
What I am trying to achieve :</p>
<ul>
<li>Select which blogs to display (by ID)</li>
<li>Select how many post to display (My code selects how many post <strong>per blog</strong>)</li>
<li><p>Order by date or random</p>
<pre><code>$blogs = get_last_updated();
foreach ($blogs AS $blog) {
switch_to_blog($blog["blog_id"]);
$lastposts = get_posts('numberposts=3');
foreach($lastposts as $post) : ?>
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php endforeach;
restore_current_blog();
}
</code></pre></li>
</ul>
| [
{
"answer_id": 267876,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": true,
"text": "<p>I created a plugin which does something similar (called Multisite Post Display <a href=\"https://wordpress.org/plugins/multisite-post-reader/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multisite-post-reader/</a> ) . It displays posts from all multisite sub-sites.</p>\n\n<p>The code in there might be helpful for what you are doing. You are welcome to dig into it and use the code to help with your project. (After all, I used other people's code snippets to develop it.)</p>\n\n<p>I wrote it after I did the Multisite Media Display, since I wanted a way to display media from subsites on one page, and couldn't find any plugin that did that. Both have been useful to monitor posted media and content from my multisite.</p>\n\n<p>Free, open source, and all that. Hope it is helpful.</p>\n"
},
{
"answer_id": 278250,
"author": "Bastian Immanuel André",
"author_id": 106223,
"author_profile": "https://wordpress.stackexchange.com/users/106223",
"pm_score": 1,
"selected": false,
"text": "<p>Ricks Answer is surely helpful but I wanted to share my approach, which is an adoption or extension of your code:</p>\n\n<p>First get a list of selected blogs in your network.:</p>\n\n<pre><code>$args = array('site__in' => array(2, 3, 6))\n$sitesObj = get_sites($args);\n$sites = object_to_array($sitesObj);\n</code></pre>\n\n<p>You can also exclude sites by using <code>'site__not_in'</code> in the arguments of <code>get_sites()</code>. </p>\n\n<p>Convert the <code>$sitesObj</code> object into an array:</p>\n\n<pre><code>$sites = object_to_array($sitesObj);\n\nobject_to_array($object) {\n if (!is_object($object) && !is_array($object)) {\n return $object;\n }\n return array_map('object_to_array', (array) $object) ;\n}\n</code></pre>\n\n<p>Then initialize a counter to control the total of posts to show and switch to each selected blog to fire the loop with your custom arguments:</p>\n\n<pre><code>$postCounter = 0;\n$maxPosts = 5; // total number of posts to show\n\nforeach ($sites as $site) {\n switch_to_blog($site['blog_id']);\n\n $args = array(\n 'post_type' => 'post', // or custom post type\n 'posts_per_page' => 2, // number of posts per blog\n 'order' => 'DESC',\n 'orderby' => 'date' // you could also use 'rand' here\n );\n\n $loop = new WP_Query($args);\n\n if ($loop->have_posts()) :\n while ($loop->have_posts() && $counter < $maxPosts) : $loop->the_post();\n // your output\n endwhile;\n endif;\n\n restore_current_blog();\n}\n</code></pre>\n\n<p>I hope that helps :)</p>\n"
},
{
"answer_id": 294959,
"author": "Skeffonics",
"author_id": 137437,
"author_profile": "https://wordpress.stackexchange.com/users/137437",
"pm_score": 0,
"selected": false,
"text": "<p>This</p>\n\n<pre><code>function wolpostcount_shortcode($atts) {\n\n function object_to_array($object) {\n if (!is_object($object) && !is_array($object)) {\n return $object;\n }\n return array_map('object_to_array', (array) $object) ;\n }\n\n $args = array('site__in' => array(1,7,8,12,14,15,20,21,22,25,32,33,36,41,42,46,47,48,49));\n $sitesObj = get_sites($args);\n $sites = object_to_array($sitesObj);\n\n foreach ($sites as $site) {\n switch_to_blog($site['blog_id']);\n\n $postcount = wp_count_posts('post')->publish;\n $pagecount = wp_count_posts('page')->publish;\n echo 'Posts:'.$postcount.' Pages:'.$pagecount.'<br>';\n $totalpostcount = $totalpostcount + $postcount;\n $totalpagecount = $totalpagecount + $pagecount;\n restore_current_blog();\n }\n\n echo 'number of posts '.$totalpostcount.'<br>';\n echo 'number of pages '.$totalpagecount.'<br>';\n</code></pre>\n"
},
{
"answer_id": 372562,
"author": "Sudip Debnath",
"author_id": 192796,
"author_profile": "https://wordpress.stackexchange.com/users/192796",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function get_all_networks_posts($args){\n if(!$args){\n return false;\n }\n $sites = get_sites();\n $blog_posts = array();\n if($sites){\n foreach ($sites as $site) {\n switch_to_blog($site->id);\n $posts = get_posts($args);\n $blog_posts[$site->id] = $posts; // this is the above line\n //$blog_posts[] = $posts;If you do not need site ids then use this line removing just the above line\n }\n }\n restore_current_blog();\n if($blog_posts){\n return $blog_posts;\n }\n}\n\n// Print a demo\n$args = arrat(\n 'post_type' => 'post',\n 'posts_per_page' => -1,\n);\nprint_r(get_all_networks_posts($args));\n</code></pre>\n"
},
{
"answer_id": 372564,
"author": "t3chernobyl",
"author_id": 59113,
"author_profile": "https://wordpress.stackexchange.com/users/59113",
"pm_score": 0,
"selected": false,
"text": "<p>A while ago I wrote a little internal plugin to show posts from the main site (where the blog is) on the subsite in the network. Also I wanted to only show posts from a specific category on a certain subsite.</p>\n<pre><code>function custom_multiblog ( $atts ) {\n // Get current blog\n $original_blog_id = get_current_blog_id();\n\n // Setup a category for each blog id you want to loop through - EDIT\n if ( 19 == $original_blog_id ) {\n $catslug_per_blog_id = array( 1 => 'category1', );\n } else if ( 22 == $original_blog_id ) {\n $catslug_per_blog_id = array( 1 => 'category2', );\n } else if ( 23 == $original_blog_id ) {\n $catslug_per_blog_id = array( 1 => 'category3', );\n } else {\n $catslug_per_blog_id = array( 1 => 'category1, category2, category3', );\n }\n \n foreach( $catslug_per_blog_id as $bid => $catslug ) {\n //Switch to the blog with the blog id $bid\n switch_to_blog( $bid ); \n $args = array(\n //'post_type' => 'post',\n 'category_name' => $catslug,\n 'posts_per_page' => 10,\n );\n $args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;\n \n echo '<div class="multiblog-wrapper">';\n $query = new WP_Query( $args );\n\n while( $query->have_posts() ) : $query->the_post();\n echo '<article class="multiblog-item">';\n echo '<div class="multiblog-img"><a href="' .get_the_permalink() . '">';\n the_post_thumbnail ('large');\n echo '</a></div>';\n echo '<div class="multiblog-content">';\n echo '<h2 style="line-height: 1em;"><a href="' .get_the_permalink() . '">' . get_the_title() . '</a></h2>';\n echo '<p>' . get_the_excerpt() . '</p>';\n echo '</div>';\n echo '<div class="clearfix"></div>';\n echo '</article>'; \n endwhile;\n \n echo '</div>';\n }\n\n switch_to_blog( $original_blog_id ); \n wp_reset_postdata();\n echo '<div class="clearfix"></div>';\n echo '<div class="multiblog-navigation">';\n previous_posts_link( '<< newer' );\n next_posts_link( 'older >>', $query->max_num_pages );\n echo '</div>';\n\n}\nadd_shortcode( 'multiblog', 'jetzt_konf_multiblog' );\n</code></pre>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33719/"
]
| The following code gives all posts from the network.
What I am trying to achieve :
* Select which blogs to display (by ID)
* Select how many post to display (My code selects how many post **per blog**)
* Order by date or random
```
$blogs = get_last_updated();
foreach ($blogs AS $blog) {
switch_to_blog($blog["blog_id"]);
$lastposts = get_posts('numberposts=3');
foreach($lastposts as $post) : ?>
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php endforeach;
restore_current_blog();
}
``` | I created a plugin which does something similar (called Multisite Post Display <https://wordpress.org/plugins/multisite-post-reader/> ) . It displays posts from all multisite sub-sites.
The code in there might be helpful for what you are doing. You are welcome to dig into it and use the code to help with your project. (After all, I used other people's code snippets to develop it.)
I wrote it after I did the Multisite Media Display, since I wanted a way to display media from subsites on one page, and couldn't find any plugin that did that. Both have been useful to monitor posted media and content from my multisite.
Free, open source, and all that. Hope it is helpful. |
257,046 | <p>I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link. </p>
<p>I am using the code here: <a href="https://www.gravityhelp.com/forums/topic/using-cookies-to-populate-forms#post-74281" rel="noreferrer">Gravity Help</a> to populate the coupon field based on the cookie. Just the second half of the code.</p>
<p>I need to set the coupon code in a cookie. There is a piece here: <a href="https://wordpress.stackexchange.com/questions/243170/setting-cookie-using-a-variable-from-the-url">Setting a Cookie using a variable from the URL</a> But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set?</p>
| [
{
"answer_id": 257051,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>Yes you just need to wrap in an <code>isset</code> check before setting the cookie:</p>\n\n<pre><code>$name = 'cookiename';\n$expires = time() + 3600;\nif (isset($_GET['code'])) {\n $value = $_GET['code'];\n setcookie($name, $value, $expires, '/', COOKIE_DOMAIN);\n}\n</code></pre>\n"
},
{
"answer_id": 257053,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 4,
"selected": true,
"text": "<p>Just check if the variable is set, using the code from your link:</p>\n\n<pre><code>add_action( 'init', 'set_agent_cookie' );\n\nfunction set_agent_cookie() {\n if (isset($_GET['code'])) {\n $name = 'agent';\n $id = $_GET['code']; \n setcookie( $name, $id, time() + 3600, \"/\", COOKIE_DOMAIN );\n }\n}\n</code></pre>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
]
| I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link.
I am using the code here: [Gravity Help](https://www.gravityhelp.com/forums/topic/using-cookies-to-populate-forms#post-74281) to populate the coupon field based on the cookie. Just the second half of the code.
I need to set the coupon code in a cookie. There is a piece here: [Setting a Cookie using a variable from the URL](https://wordpress.stackexchange.com/questions/243170/setting-cookie-using-a-variable-from-the-url) But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set? | Just check if the variable is set, using the code from your link:
```
add_action( 'init', 'set_agent_cookie' );
function set_agent_cookie() {
if (isset($_GET['code'])) {
$name = 'agent';
$id = $_GET['code'];
setcookie( $name, $id, time() + 3600, "/", COOKIE_DOMAIN );
}
}
``` |
257,055 | <p>First time I faced this problem & trying to find out solution but it seems to me that it happens very few and that is why no more solution has been found like this & that is why I am here.</p>
<p>WordPress Import Message:</p>
<blockquote>
<p>File is empty. Please upload something more
substantial. This error could also be caused by uploads being disabled
in your <code>php.ini</code> or by <code>post_max_size</code> being defined as smaller than
<code>upload_max_filesize</code> in <code>php.ini</code>.</p>
</blockquote>
<p>I am getting above message when trying to import a previously imported file like the bellow image. Could you please tell me how to solve this?</p>
<p><a href="https://i.stack.imgur.com/4A1Qg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4A1Qg.jpg" alt="enter image description here"></a></p>
<p>I already tried to find the solution by googling but could not yet? </p>
| [
{
"answer_id": 257066,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 3,
"selected": true,
"text": "<p>You need to increase the upload limit in your <code>php.ini</code>.</p>\n<p>To increase the maximum upload file size, open your php.ini file in the "<code>xampp/php/php.ini</code>" directory. search for <code>upload_max_filesize</code> and increase the value like :</p>\n<pre><code>upload_max_filesize = 128M\n</code></pre>\n"
},
{
"answer_id": 300978,
"author": "Tom Spark",
"author_id": 141897,
"author_profile": "https://wordpress.stackexchange.com/users/141897",
"pm_score": 1,
"selected": false,
"text": "<p>In order to fix this problem, you need to navigate into your cpanel and change the PHP functions to increase the size. </p>\n\n<p>Source: <a href=\"https://www.youtube.com/watch?v=lGJrlvV_vQ4\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=lGJrlvV_vQ4</a></p>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113702/"
]
| First time I faced this problem & trying to find out solution but it seems to me that it happens very few and that is why no more solution has been found like this & that is why I am here.
WordPress Import Message:
>
> File is empty. Please upload something more
> substantial. This error could also be caused by uploads being disabled
> in your `php.ini` or by `post_max_size` being defined as smaller than
> `upload_max_filesize` in `php.ini`.
>
>
>
I am getting above message when trying to import a previously imported file like the bellow image. Could you please tell me how to solve this?
[](https://i.stack.imgur.com/4A1Qg.jpg)
I already tried to find the solution by googling but could not yet? | You need to increase the upload limit in your `php.ini`.
To increase the maximum upload file size, open your php.ini file in the "`xampp/php/php.ini`" directory. search for `upload_max_filesize` and increase the value like :
```
upload_max_filesize = 128M
``` |
257,071 | <p>I need to get the ID posts for which the category(taxonomy "category") is not specified.
Post include other taxonomy.</p>
<p>I get posts from code:</p>
<pre><code>$posts = $wpdb->get_results('SELECT ...', , ARRAY_A);
</code></pre>
<p>My query selects the desired type of recording</p>
<pre><code>SELECT distinct posts.ID FROM wp_posts AS posts
LEFT JOIN wp_term_relationships AS cat_link ON
cat_link.object_id = posts.ID
LEFT JOIN wp_term_taxonomy AS cat_tax ON
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
WHERE post_type = 'popular_music' AND post_status = 'publish' ORDER BY posts.ID DESC
</code></pre>
<p>But it is not considered:</p>
<pre><code>cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
</code></pre>
<p>How to select the record, Uncategorized?</p>
| [
{
"answer_id": 257072,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>The SQL you're after is something similar to this:</p>\n\n<pre><code>SELECT *\nFROM wp_posts AS posts\n LEFT JOIN wp_term_relationships \n AS cat_link\n ON cat_link.object_id = posts.ID\n LEFT JOIN wp_term_taxonomy\n AS cat_tax\n ON cat_tax.term_taxonomy_id = cat_link.term_taxonomy_id\n AND cat_tax.taxonomy = 'category'\nWHERE post_type = 'post'\nAND post_status = 'publish'\nAND cat_link.object_id IS NULL\n</code></pre>\n"
},
{
"answer_id": 257087,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand the question, you're looking for the SQL for the equivalent of</p>\n\n<pre><code>$args = array (\n 'post_type' => 'popular_music',\n 'post_status' => 'publish',\n 'tax_query' => array (\n array (\n 'taxonomy' => 'category',\n 'operator' => 'NOT EXISTS',\n ),\n ),\n 'posts_per_page' => -1,\n 'orderby' => 'ID',\n 'order' => 'DESC',\n ) ;\n$query = new WP_Query ($args) ;\necho $query->request ;\n</code></pre>\n\n<p>If so, then this is the SQL that WP_Query produces</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID\nFROM\n $wpdb->posts\nWHERE\n 1=1 AND\n ( \n NOT EXISTS\n (\n SELECT 1\n FROM\n $wpdb->term_relationships INNER JOIN\n $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id\n WHERE\n $wpdb->term_taxonomy.taxonomy = 'category' AND\n $wpdb->term_relationships.object_id = $wpdb->posts.ID\n )\n ) AND\n $wpdb->posts.post_type = 'popular_music' AND\n (($wpdb->posts.post_status = 'publish'))\nGROUP BY $wpdb->posts.ID\nORDER BY $wpdb->posts.ID DESC\n</code></pre>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111011/"
]
| I need to get the ID posts for which the category(taxonomy "category") is not specified.
Post include other taxonomy.
I get posts from code:
```
$posts = $wpdb->get_results('SELECT ...', , ARRAY_A);
```
My query selects the desired type of recording
```
SELECT distinct posts.ID FROM wp_posts AS posts
LEFT JOIN wp_term_relationships AS cat_link ON
cat_link.object_id = posts.ID
LEFT JOIN wp_term_taxonomy AS cat_tax ON
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
WHERE post_type = 'popular_music' AND post_status = 'publish' ORDER BY posts.ID DESC
```
But it is not considered:
```
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
```
How to select the record, Uncategorized? | If I understand the question, you're looking for the SQL for the equivalent of
```
$args = array (
'post_type' => 'popular_music',
'post_status' => 'publish',
'tax_query' => array (
array (
'taxonomy' => 'category',
'operator' => 'NOT EXISTS',
),
),
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'DESC',
) ;
$query = new WP_Query ($args) ;
echo $query->request ;
```
If so, then this is the SQL that WP\_Query produces
```
SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID
FROM
$wpdb->posts
WHERE
1=1 AND
(
NOT EXISTS
(
SELECT 1
FROM
$wpdb->term_relationships INNER JOIN
$wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE
$wpdb->term_taxonomy.taxonomy = 'category' AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
) AND
$wpdb->posts.post_type = 'popular_music' AND
(($wpdb->posts.post_status = 'publish'))
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.ID DESC
``` |
257,073 | <p>I need to parse widget content based on it's ID.</p>
<p>But a widget works like a function that pulls data based on it's arguments, right? So when I pull the widget data, I can only get it's arguments, not the actual output.</p>
<p>How can I parse the widget content based on it's ID?</p>
<p>Example code:</p>
<pre><code>// Update widget rounds automatically
function automatize_games_rounds($instance, $widget, $args){
// Check if there is a caption
if (isset($instance['caption']) && !empty($instance['caption'])) {
// If there is, does it contain the word "round"?
if (strpos(strtolower($instance['caption']), 'round')) {
// If yes, it's the kind of widget I'm looking for. Let's get it's ID.
$id = $args['widget_id'];
// Now I need to parse the widget output to do some stuff based on it's content, but how can I get the widget output?
}
}
return $instance;
}
add_filter('widget_display_callback','automatize_games_rounds',10,3);
</code></pre>
| [
{
"answer_id": 257072,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>The SQL you're after is something similar to this:</p>\n\n<pre><code>SELECT *\nFROM wp_posts AS posts\n LEFT JOIN wp_term_relationships \n AS cat_link\n ON cat_link.object_id = posts.ID\n LEFT JOIN wp_term_taxonomy\n AS cat_tax\n ON cat_tax.term_taxonomy_id = cat_link.term_taxonomy_id\n AND cat_tax.taxonomy = 'category'\nWHERE post_type = 'post'\nAND post_status = 'publish'\nAND cat_link.object_id IS NULL\n</code></pre>\n"
},
{
"answer_id": 257087,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand the question, you're looking for the SQL for the equivalent of</p>\n\n<pre><code>$args = array (\n 'post_type' => 'popular_music',\n 'post_status' => 'publish',\n 'tax_query' => array (\n array (\n 'taxonomy' => 'category',\n 'operator' => 'NOT EXISTS',\n ),\n ),\n 'posts_per_page' => -1,\n 'orderby' => 'ID',\n 'order' => 'DESC',\n ) ;\n$query = new WP_Query ($args) ;\necho $query->request ;\n</code></pre>\n\n<p>If so, then this is the SQL that WP_Query produces</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID\nFROM\n $wpdb->posts\nWHERE\n 1=1 AND\n ( \n NOT EXISTS\n (\n SELECT 1\n FROM\n $wpdb->term_relationships INNER JOIN\n $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id\n WHERE\n $wpdb->term_taxonomy.taxonomy = 'category' AND\n $wpdb->term_relationships.object_id = $wpdb->posts.ID\n )\n ) AND\n $wpdb->posts.post_type = 'popular_music' AND\n (($wpdb->posts.post_status = 'publish'))\nGROUP BY $wpdb->posts.ID\nORDER BY $wpdb->posts.ID DESC\n</code></pre>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| I need to parse widget content based on it's ID.
But a widget works like a function that pulls data based on it's arguments, right? So when I pull the widget data, I can only get it's arguments, not the actual output.
How can I parse the widget content based on it's ID?
Example code:
```
// Update widget rounds automatically
function automatize_games_rounds($instance, $widget, $args){
// Check if there is a caption
if (isset($instance['caption']) && !empty($instance['caption'])) {
// If there is, does it contain the word "round"?
if (strpos(strtolower($instance['caption']), 'round')) {
// If yes, it's the kind of widget I'm looking for. Let's get it's ID.
$id = $args['widget_id'];
// Now I need to parse the widget output to do some stuff based on it's content, but how can I get the widget output?
}
}
return $instance;
}
add_filter('widget_display_callback','automatize_games_rounds',10,3);
``` | If I understand the question, you're looking for the SQL for the equivalent of
```
$args = array (
'post_type' => 'popular_music',
'post_status' => 'publish',
'tax_query' => array (
array (
'taxonomy' => 'category',
'operator' => 'NOT EXISTS',
),
),
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'DESC',
) ;
$query = new WP_Query ($args) ;
echo $query->request ;
```
If so, then this is the SQL that WP\_Query produces
```
SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID
FROM
$wpdb->posts
WHERE
1=1 AND
(
NOT EXISTS
(
SELECT 1
FROM
$wpdb->term_relationships INNER JOIN
$wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE
$wpdb->term_taxonomy.taxonomy = 'category' AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
) AND
$wpdb->posts.post_type = 'popular_music' AND
(($wpdb->posts.post_status = 'publish'))
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.ID DESC
``` |
257,085 | <p>When viewing the home page of my site (<a href="http://zilredloh.com" rel="nofollow noreferrer">zilredloh.com</a>), sometimes I do not see the latest posts. A new post will have been published, but the main index page doesn't reflect this. Refreshing the browser via F5 will then show the new content.</p>
<p>I know that browsers will sometimes cache content, but I have not encountered such a significant caching problem before for other sites. This issue seems to happen sporadically, and I've seen it occur while using different browsers and from different locations.</p>
<p>This morning, I opened up the site in Safari. The most recent post displayed was dated February 10. However, there were two posts made after this time - and they don't show up at all:</p>
<p><a href="https://avoision.com/dev/whb/Screen%20Shot%202017-02-19%20at%206.17.44%20AM.png" rel="nofollow noreferrer">Screenshot of Safari, Dev Tools</a></p>
<p>I know that if I refresh, or if I clear my browser cache - I will see the most recent content. That's not my issue. What I want to understand is where this caching is coming from in the first place. </p>
<p>In the screenshot above, I see a 200 Status for most assets requested. Some assets though (like Google Fonts, Google Analytics, and wp.pixel.com) are not cached. </p>
<p>Is this entirely due to the browser's cache? It seems unusually aggressive if so. I've reached out to my host (WebHostingBuzz), but they are telling me "There is no caching in cPanel by default." </p>
<ul>
<li>I have seen this sporadic issue in Chrome, Firefox, and Safari (Mac). </li>
<li>I am using a Child Theme, based off of a <a href="https://themeforest.net/item/writsy-a-clean-faded-vintage-wordpress-blog-theme/16106738" rel="nofollow noreferrer">custom theme</a>.</li>
<li>I have some plugins installed, but no cache-related plugins installed.</li>
</ul>
<p>I've made direct changes to my child theme's style.css file on the server, and after a refresh - those changes appear instantly and successfully. </p>
<p>Refreshing always seems to retrieve the latest and most recent files/posts, but on occasion when returning to the site... I seem to be getting a cached view. And I'm unclear why. </p>
<p>I would appreciate any suggestions or advice on where to focus my troubleshooting. </p>
<p>Thanks,
-Felix</p>
<hr>
<p>Traceroute results: <a href="https://avoision.com/dev/wpse/traceroute-zilredloh-local.png" rel="nofollow noreferrer">Local</a> vs. <a href="https://avoision.com/dev/wpse/traceroute-zilredloh-pingeu.png" rel="nofollow noreferrer">ping.eu</a></p>
| [
{
"answer_id": 257088,
"author": "Matt",
"author_id": 32255,
"author_profile": "https://wordpress.stackexchange.com/users/32255",
"pm_score": 0,
"selected": false,
"text": "<p>To narrow it down, perhaps try disabling cache in your browser. In Chrome - [Developer tools] > [Network] and tick the box that says \"Disable cache\".</p>\n"
},
{
"answer_id": 257107,
"author": "JpaytonWPD",
"author_id": 70863,
"author_profile": "https://wordpress.stackexchange.com/users/70863",
"pm_score": 2,
"selected": true,
"text": "<p>You may need to set nocache headers in your main template header. Include this near the top of the header.php after the opening tag: <code>nocache_headers()</code></p>\n\n<p>From here: <a href=\"https://codex.wordpress.org/Function_Reference/nocache_headers\" rel=\"nofollow noreferrer\">Function Reference/nocache headers</a></p>\n\n<p>Run some tests, I believe this should only affect the main page file, other files should still cache normally. </p>\n\n<p>More idealy, wordpress should be sending a last modified header with the home page. Hold on while I dig further into this. </p>\n\n<p>Notice the cache-control max-age. As you can see, the cache has been set at 30 days. Meaning the browser will assume nothing has changed for 30 days unless the server sends a different header. </p>\n\n<pre><code>HTTP/1.1 200 OK\nX-Powered-By: PHP/5.4.45\nCache-Control: public, max-age=2592000\nExpires: Wed, 22 Mar 2017 01:15:09 GMT\nContent-Type: text/html; charset=UTF-8\nLink: <http://zilredloh.com/wp-json/>; rel=\"https://api.w.org/\"\nLink: <http://wp.me/1ZLfW>; rel=shortlink\nVary: Accept-Encoding\nDate: Mon, 20 Feb 2017 01:15:09 GMT\nAccept-Ranges: bytes\nServer: LiteSpeed\nConnection: close\nContent-Length: 85258\n</code></pre>\n\n<h2>After adding the code:</h2>\n\n<p>Notice the second set of Cache Control and Expires.</p>\n\n<pre><code>HTTP/1.1 200 OK\nX-Powered-By: PHP/5.4.45\nCache-Control: public, max-age=2592000\nExpires: Wed, 22 Mar 2017 02:01:16 GMT\nContent-Type: text/html; charset=UTF-8\nLink: <http://zilredloh.com/wp-json/>; rel=\"https://api.w.org/\"\nLink: <http://wp.me/1ZLfW>; rel=shortlink\nExpires: Wed, 11 Jan 1984 05:00:00 GMT\nCache-Control: no-cache, must-revalidate, max-age=0\nVary: Accept-Encoding\nDate: Mon, 20 Feb 2017 02:01:16 GMT\nAccept-Ranges: bytes\nServer: LiteSpeed\nConnection: close\nContent-Length: 85258\n</code></pre>\n"
}
]
| 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112846/"
]
| When viewing the home page of my site ([zilredloh.com](http://zilredloh.com)), sometimes I do not see the latest posts. A new post will have been published, but the main index page doesn't reflect this. Refreshing the browser via F5 will then show the new content.
I know that browsers will sometimes cache content, but I have not encountered such a significant caching problem before for other sites. This issue seems to happen sporadically, and I've seen it occur while using different browsers and from different locations.
This morning, I opened up the site in Safari. The most recent post displayed was dated February 10. However, there were two posts made after this time - and they don't show up at all:
[Screenshot of Safari, Dev Tools](https://avoision.com/dev/whb/Screen%20Shot%202017-02-19%20at%206.17.44%20AM.png)
I know that if I refresh, or if I clear my browser cache - I will see the most recent content. That's not my issue. What I want to understand is where this caching is coming from in the first place.
In the screenshot above, I see a 200 Status for most assets requested. Some assets though (like Google Fonts, Google Analytics, and wp.pixel.com) are not cached.
Is this entirely due to the browser's cache? It seems unusually aggressive if so. I've reached out to my host (WebHostingBuzz), but they are telling me "There is no caching in cPanel by default."
* I have seen this sporadic issue in Chrome, Firefox, and Safari (Mac).
* I am using a Child Theme, based off of a [custom theme](https://themeforest.net/item/writsy-a-clean-faded-vintage-wordpress-blog-theme/16106738).
* I have some plugins installed, but no cache-related plugins installed.
I've made direct changes to my child theme's style.css file on the server, and after a refresh - those changes appear instantly and successfully.
Refreshing always seems to retrieve the latest and most recent files/posts, but on occasion when returning to the site... I seem to be getting a cached view. And I'm unclear why.
I would appreciate any suggestions or advice on where to focus my troubleshooting.
Thanks,
-Felix
---
Traceroute results: [Local](https://avoision.com/dev/wpse/traceroute-zilredloh-local.png) vs. [ping.eu](https://avoision.com/dev/wpse/traceroute-zilredloh-pingeu.png) | You may need to set nocache headers in your main template header. Include this near the top of the header.php after the opening tag: `nocache_headers()`
From here: [Function Reference/nocache headers](https://codex.wordpress.org/Function_Reference/nocache_headers)
Run some tests, I believe this should only affect the main page file, other files should still cache normally.
More idealy, wordpress should be sending a last modified header with the home page. Hold on while I dig further into this.
Notice the cache-control max-age. As you can see, the cache has been set at 30 days. Meaning the browser will assume nothing has changed for 30 days unless the server sends a different header.
```
HTTP/1.1 200 OK
X-Powered-By: PHP/5.4.45
Cache-Control: public, max-age=2592000
Expires: Wed, 22 Mar 2017 01:15:09 GMT
Content-Type: text/html; charset=UTF-8
Link: <http://zilredloh.com/wp-json/>; rel="https://api.w.org/"
Link: <http://wp.me/1ZLfW>; rel=shortlink
Vary: Accept-Encoding
Date: Mon, 20 Feb 2017 01:15:09 GMT
Accept-Ranges: bytes
Server: LiteSpeed
Connection: close
Content-Length: 85258
```
After adding the code:
----------------------
Notice the second set of Cache Control and Expires.
```
HTTP/1.1 200 OK
X-Powered-By: PHP/5.4.45
Cache-Control: public, max-age=2592000
Expires: Wed, 22 Mar 2017 02:01:16 GMT
Content-Type: text/html; charset=UTF-8
Link: <http://zilredloh.com/wp-json/>; rel="https://api.w.org/"
Link: <http://wp.me/1ZLfW>; rel=shortlink
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Vary: Accept-Encoding
Date: Mon, 20 Feb 2017 02:01:16 GMT
Accept-Ranges: bytes
Server: LiteSpeed
Connection: close
Content-Length: 85258
``` |
257,105 | <p>I have a child theme where I'm using the old @import to import in the CSS and I know this is no longer best practice. I've seen on the Wordpress codex how to do this properly, which seems straightforward enough, but I need to find the $handle used in the parent theme when it registers its stylesheet.</p>
<p>This is the code they give:</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>How do I find out the parent theme's style.css $handle so i can swap it for 'parent-style' that is used above? (the theme I'm using is Divi, but I'd like to know how to find this because I do use other themes).</p>
<p>Thanks,</p>
<p>Emily</p>
| [
{
"answer_id": 257113,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 0,
"selected": false,
"text": "<p>That is not possible using a theme, you need to do it manually, or you will have to find a <code>plugin</code> that saves that data and in your themes retrieve that data.</p>\n\n<p>The advantage of the <code>plugin</code> is that if the parent themes have a complex structure you will not have to search each file for the <code>wp_enqueue_style</code> and copy paste the handler, you will use either a <code>get_option</code> or a <code>function</code> that the plugin will provide either way you have to go into each <code>child-theme</code> and update that value.</p>\n"
},
{
"answer_id": 257117,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>$handle</code> in this case is just a name to identify the stylesheet that being referenced, and is hardcoded in PHP as a value and cannot be found anywhere.</p>\n\n<p>In fact, the <code>parent-style</code> is going to be the <code>id</code> of the stylesheet being enqueued, and WordPress will generate the following HTML code for you:</p>\n\n<p><code><link id=\"parent-style-css\" rel=\"stylesheet\" href=\"THE PARENT STYLE CSS URL\"/></code></p>\n\n<p>Noticed the <code>parent-style</code> value being used in the ID and then suffixed with <strong>css</strong></p>\n"
},
{
"answer_id": 286244,
"author": "Boris Chevreau",
"author_id": 131692,
"author_profile": "https://wordpress.stackexchange.com/users/131692",
"pm_score": 3,
"selected": false,
"text": "<p>To clarify this, for anyone using Divi theme (but generally any WP theme), a simple inspection using Dev tools on the \"head\" for the stylesheet links usually gives a clue about the handle, as Den Isahac mentioned previously (it wasn't clear as he mentioned it can't be found).</p>\n\n<p><strong>Anything before the \"-css\" on the ID of the link for the stylesheet of the Parent theme is generally that handle.</strong></p>\n\n<p>Example below with Divi, id=\"divi-style-css\" thus $handle = 'divi-style\"</p>\n\n<p><a href=\"https://i.stack.imgur.com/kdPJU.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kdPJU.jpg\" alt=\"Above is template style with id='divi-style-css' , and below the child\"></a></p>\n\n<p>Thus for Divi, you would enqueue theme like this:</p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()->get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n\n<p>Little bonus:\nBrowsers have an annoying tendency of caching the child stylesheet depending on its \"Version\". The drawback is that it prevents you from ever seeing your edits even after refreshing / clearing cache, unless you change the \"Version\" number in your css file after every edit. </p>\n\n<p>You can change this behavior by swapping <strong>wp_get_theme()->get('Version')</strong> (the $ver parameter) for the handy <strong>filemtime( get_stylesheet_directory() . '/style.css' )</strong> instead, which adds a version number after the stylesheet corresponding to the timestamp from the last time you saved your child stylesheet, instead of the true \"Version\" declared in that stylesheet. You can eventually revert to the regular function before going live, but it can be extremely helpful during production.</p>\n\n<p>The whole enqueue script for Divi would thus become:</p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n\n $parent_style = 'divi-style'; // This is 'Divi' style referrence for the Divi theme.\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n filemtime( get_stylesheet_directory() . '/style.css' )\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
]
| I have a child theme where I'm using the old @import to import in the CSS and I know this is no longer best practice. I've seen on the Wordpress codex how to do this properly, which seems straightforward enough, but I need to find the $handle used in the parent theme when it registers its stylesheet.
This is the code they give:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
How do I find out the parent theme's style.css $handle so i can swap it for 'parent-style' that is used above? (the theme I'm using is Divi, but I'd like to know how to find this because I do use other themes).
Thanks,
Emily | To clarify this, for anyone using Divi theme (but generally any WP theme), a simple inspection using Dev tools on the "head" for the stylesheet links usually gives a clue about the handle, as Den Isahac mentioned previously (it wasn't clear as he mentioned it can't be found).
**Anything before the "-css" on the ID of the link for the stylesheet of the Parent theme is generally that handle.**
Example below with Divi, id="divi-style-css" thus $handle = 'divi-style"
[](https://i.stack.imgur.com/kdPJU.jpg)
Thus for Divi, you would enqueue theme like this:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
Little bonus:
Browsers have an annoying tendency of caching the child stylesheet depending on its "Version". The drawback is that it prevents you from ever seeing your edits even after refreshing / clearing cache, unless you change the "Version" number in your css file after every edit.
You can change this behavior by swapping **wp\_get\_theme()->get('Version')** (the $ver parameter) for the handy **filemtime( get\_stylesheet\_directory() . '/style.css' )** instead, which adds a version number after the stylesheet corresponding to the timestamp from the last time you saved your child stylesheet, instead of the true "Version" declared in that stylesheet. You can eventually revert to the regular function before going live, but it can be extremely helpful during production.
The whole enqueue script for Divi would thus become:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'divi-style'; // This is 'Divi' style referrence for the Divi theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
filemtime( get_stylesheet_directory() . '/style.css' )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` |
257,108 | <p>I want to remove the WordPress version from my Source Code. To achieve this, I have placed the following code in my functions.php file:</p>
<pre><code>function wordpress_remove_version() {
return '';
}
add_filter('the_generator', 'wordpress_remove_version');
</code></pre>
<p>This code has worked for me in the past but for some reason, the WordPress version is still appearing in my Source Code. </p>
<p>I have deactivated my Plugins but still with no success. Nor has trailing the internet for any updates on new codes etc. </p>
<p>Has anyone else got this problem or know of where may be going wrong? </p>
| [
{
"answer_id": 257109,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>Your code works for me in version 4.7.2 with 2016 theme, but a slightly simpler version is to remove the action entirely rather than filter the output:</p>\n\n<pre><code>remove_action( 'wp_head', 'wp_generator' );\n</code></pre>\n"
},
{
"answer_id": 257425,
"author": "Craig",
"author_id": 112472,
"author_profile": "https://wordpress.stackexchange.com/users/112472",
"pm_score": 1,
"selected": true,
"text": "<p>I have figured out the problem!</p>\n\n<p>For anyone reading this, my code does work perfectly fine. The issue lied within my functions.php file.</p>\n\n<p>Rather than have the following in my file:</p>\n\n<pre><code>function theme_name_script_enqueue() {\n\nwp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css', array(), '1.0', true );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );\n</code></pre>\n\n<p>I had ...</p>\n\n<pre><code>function theme_name_script_enqueue() {\n\nwp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );\n</code></pre>\n\n<p>Note that I was missing <code>, array(), '1.0', true</code></p>\n\n<p>Once the above was inserted, all worked perfectly fine.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112472/"
]
| I want to remove the WordPress version from my Source Code. To achieve this, I have placed the following code in my functions.php file:
```
function wordpress_remove_version() {
return '';
}
add_filter('the_generator', 'wordpress_remove_version');
```
This code has worked for me in the past but for some reason, the WordPress version is still appearing in my Source Code.
I have deactivated my Plugins but still with no success. Nor has trailing the internet for any updates on new codes etc.
Has anyone else got this problem or know of where may be going wrong? | I have figured out the problem!
For anyone reading this, my code does work perfectly fine. The issue lied within my functions.php file.
Rather than have the following in my file:
```
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
```
I had ...
```
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
```
Note that I was missing `, array(), '1.0', true`
Once the above was inserted, all worked perfectly fine. |
257,111 | <p>In response to the <a href="https://wordpress.stackexchange.com/questions/257085/help-pinpointing-source-of-caching-issue">question asked here</a> I find myself and this other user needing a solution to set a last modified header that contains the date and time of the most reicent post. Since we both in many themes have the home page set to a static page and then coding our dynamic content into the static files we are missing that important header to make sure cached homepages update when there are new posts. </p>
<p>So, how can we set a last modified HTTP header on a page that it set to the most recent Post?</p>
| [
{
"answer_id": 257431,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>Untested, but it <em>should</em> work:</p>\n\n<pre><code>$query = \"SELECT MAX(post_modified) AS modified FROM {$wpdb->prefix}posts\";\n$results = $wpdb->get_results($query);\n\nif (isset($results[0]->modified) {\n header(\"Last-Modified: \".$results[0]->modified);\n}\n</code></pre>\n"
},
{
"answer_id": 257484,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": true,
"text": "<h2>Last-Modified header for visitors on the front-page</h2>\n\n<p>It's useful to see how the <em>Last-Modified</em> header is added to the feeds, in the <a href=\"https://github.com/WordPress/WordPress/blob/55df308b4d4ea733a3738d8c210ffb0ab0d7d7bf/wp-includes/class-wp.php#L399\" rel=\"nofollow noreferrer\"><code>wp::send_header()</code></a> method.</p>\n\n<p>If we want to be able to use <code>is_front_page()</code>, then the filters <code>wp_headers</code> or <code>send_header</code> are probably applied to early.</p>\n\n<p>We could instead use the <code>template_redirect</code> hook to target the front-page, before the headers are sent and after <code>is_front_page()</code> is ready. </p>\n\n<p>Here's an example:</p>\n\n<pre><code>/**\n * Set the Last-Modified header for visitors on the front-page \n * based on when a post was last modified.\n */\n\nadd_action( 'template_redirect', function() use ( &$wp )\n{\n // Only visitors (not logged in)\n if( is_user_logged_in() )\n return;\n\n // Target front-page\n if( ! is_front_page() )\n return;\n\n // Don't add it if there's e.g. 404 error (similar as the error check for feeds)\n if( ! empty( $wp->query_vars['error'] ) )\n return;\n\n // Don't override the last-modified header if it's already set\n $headers = headers_list();\n if( ! empty( $headers['last-modified'] ) ) \n return;\n\n // Get last modified post\n $last_modified = mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), false );\n\n // Add last modified header\n if( $last_modified && ! headers_sent() )\n header( \"Last-Modified: \" . $last_modified . ' GMT' );\n\n}, 1 );\n</code></pre>\n\n<p>Here we used the core PHP functions <a href=\"http://php.net/manual/en/function.header.php\" rel=\"nofollow noreferrer\"><code>header()</code></a>, <a href=\"http://php.net/manual/en/function.headers-list.php\" rel=\"nofollow noreferrer\"><code>headers_list()</code></a> and <a href=\"http://php.net/manual/en/function.headers-sent.php\" rel=\"nofollow noreferrer\"><code>headers_sent()</code></a> and the WordPress core function <a href=\"https://developer.wordpress.org/reference/functions/get_lastpostmodified/\" rel=\"nofollow noreferrer\"><code>get_lastpostmodified()</code></a></p>\n\n<p>The <em>Etag</em> header could be added here too as the <em>md5</em> of the last modified date.</p>\n\n<p>We can then test it from the command line with e.g.:</p>\n\n<pre><code># curl --head https://example.tld\n</code></pre>\n\n<p>or just use the shorthand parameter <code>-I</code> to only fetch the HTTP headers.</p>\n"
},
{
"answer_id": 367406,
"author": "header-works",
"author_id": 188721,
"author_profile": "https://wordpress.stackexchange.com/users/188721",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action('template_redirect', 'theme_add_last_modified_header');\n\nfunction theme_add_last_modified_header($headers) {\n global $post;\n if(isset($post) && isset($post->post_modified)){\n $post_mod_date=date(\"D, d M Y H:i:s\",strtotime($post->post_modified));\n header('Last-Modified: '.$post_mod_date.' GMT');\n }\n}\n</code></pre>\n\n<p>This worked for me on posts and pages :)</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
]
| In response to the [question asked here](https://wordpress.stackexchange.com/questions/257085/help-pinpointing-source-of-caching-issue) I find myself and this other user needing a solution to set a last modified header that contains the date and time of the most reicent post. Since we both in many themes have the home page set to a static page and then coding our dynamic content into the static files we are missing that important header to make sure cached homepages update when there are new posts.
So, how can we set a last modified HTTP header on a page that it set to the most recent Post? | Last-Modified header for visitors on the front-page
---------------------------------------------------
It's useful to see how the *Last-Modified* header is added to the feeds, in the [`wp::send_header()`](https://github.com/WordPress/WordPress/blob/55df308b4d4ea733a3738d8c210ffb0ab0d7d7bf/wp-includes/class-wp.php#L399) method.
If we want to be able to use `is_front_page()`, then the filters `wp_headers` or `send_header` are probably applied to early.
We could instead use the `template_redirect` hook to target the front-page, before the headers are sent and after `is_front_page()` is ready.
Here's an example:
```
/**
* Set the Last-Modified header for visitors on the front-page
* based on when a post was last modified.
*/
add_action( 'template_redirect', function() use ( &$wp )
{
// Only visitors (not logged in)
if( is_user_logged_in() )
return;
// Target front-page
if( ! is_front_page() )
return;
// Don't add it if there's e.g. 404 error (similar as the error check for feeds)
if( ! empty( $wp->query_vars['error'] ) )
return;
// Don't override the last-modified header if it's already set
$headers = headers_list();
if( ! empty( $headers['last-modified'] ) )
return;
// Get last modified post
$last_modified = mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), false );
// Add last modified header
if( $last_modified && ! headers_sent() )
header( "Last-Modified: " . $last_modified . ' GMT' );
}, 1 );
```
Here we used the core PHP functions [`header()`](http://php.net/manual/en/function.header.php), [`headers_list()`](http://php.net/manual/en/function.headers-list.php) and [`headers_sent()`](http://php.net/manual/en/function.headers-sent.php) and the WordPress core function [`get_lastpostmodified()`](https://developer.wordpress.org/reference/functions/get_lastpostmodified/)
The *Etag* header could be added here too as the *md5* of the last modified date.
We can then test it from the command line with e.g.:
```
# curl --head https://example.tld
```
or just use the shorthand parameter `-I` to only fetch the HTTP headers. |
257,114 | <p>I'm trying to get a thumbnail for my post. Like if the first custom meta box doesn't have any <code>value/content</code>, should use <code>}else if ($img =get_post_custom_values('backdrop_img')) { $imgsrc = $img[0]; }</code> (which is the 2nd metabox) then 3rd, <code>else if</code> it also doesn't have any <code>content/value</code> just use an image from my theme directory.</p>
<p>But my problem is, it only works on the first meta box, which is:</p>
<pre><code>if($img = get_post_custom_values('featured_img')){ $imgsrc = $img[0];
</code></pre>
<p>after that line the codes doesn't work and won't get values from 2nd custom meta box or use the defaul image if nothing from the conditions work.</p>
<p>I'm new to php and stil learning so i'm still confused. I'd appreciate any help.</p>
<p>So here's my code so far. </p>
<p>UPDATED: with the entire test code of the loop.</p>
<pre><code> <?php $year = date ("Y"); query_posts(array(get_option('year') => $year, 'posts_per_page' => 5, 'showposts' => 5)); ?>
<?php while (have_posts()) : the_post(); ?>
<?php if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'medium');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
if($img = get_post_custom_values('featured_img')){
$imgsrc = $img[0];
}elseif($img = get_post_custom_values('backdrop_img')){
$imgsrc = $img;
} else {
$img = get_template_directory_uri().'/movies/no_img.png';
$imgsrc = $img;
}
} ?>
<div class="post_content">
<img src="<?php echo $imgsrc; $imgsrc = ''; ?>
<a href="<?php the_permalink() ?>" class="slide-link" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<p class="sc-desc"> <?php the_excerpt(); ?></p>
</div>
<?php } endwhile; ?>
</code></pre>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the default first\n $img = get_template_directory_uri() . '/movie/no_img.png';\n $imgsrc = $img;\n\n if (has_post_thumbnail()) {\n $imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');\n $imgsrc = $imgsrc[0];\n } elseif ($postimages = get_children(\"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\")) {\n foreach ($postimages as $postimage) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n } elseif (preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match) != FALSE) {\n $imgsrc = $match[1];\n } else {\n $img = get_post_custom_values('featured_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } else {\n $img = get_post_custom_values('backdrop_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } \n\n }\n }\n //use it after all the logic\n echo $imgsrc;\n\n ?>\n</code></pre>\n\n<p>by the way if this is in the loop you can just use <code>get_the_ID</code></p>\n"
},
{
"answer_id": 257126,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>i think you have wrong this else if not right elseif is right so your else part is not execute.\ndocument link : <code>http://php.net/manual/en/control-structures.elseif.php</code></p>\n\n<p>your code like this : </p>\n\n<pre><code>else if ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>Replace with :</p>\n\n<pre><code>elseif ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>I hope it's helpful.</p>\n"
},
{
"answer_id": 257131,
"author": "Archangel17",
"author_id": 110405,
"author_profile": "https://wordpress.stackexchange.com/users/110405",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing <code>[0]</code> in <code>$imgsrc = $img[0];</code> and using <code>custom_get_meta()</code></p>\n\n<p>like: </p>\n\n<p><code>$img = post_movie_get_meta('featured_img')</code></p>\n\n<p>and:</p>\n\n<p><code>$img = post_movie_get_meta('backdrop_img')</code></p>\n"
},
{
"answer_id": 257161,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>This is not how you should use <code>elseif</code>. Note that the following <code>elseif</code> conditions will run, not matter the result of your initial <code>if()</code>. You should use nested <code>if()</code> instead.</p>\n\n<p>Take a look at this:</p>\n\n<pre><code> <?php \n $year = date (\"Y\");\n query_posts(\n array(\n get_option('year') => $year,\n 'posts_per_page' => 5,\n 'showposts' => 5)\n );\n while ( have_posts() ) : the_post(); \n if ( has_post_thumbnail() ) {\n $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );\n $imgsrc = $imgsrc[0];\n } else {\n $postimages = get_children( \"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\" );\n foreach( $postimages as $postimage ) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n if ( !$imgsrc ) {\n preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match);\n $imgsrc = $match[1];\n if (!$imgsrc){\n $img = get_post_custom_values('featured_img');\n $imgsrc = $img[0];\n if (!$imgsrc){\n $img = get_post_custom_values('backdrop_img');\n $imgsrc = $img;\n if (!$imgsrc){\n $img = get_template_directory_uri().'/movies/no_img.png';\n $imgsrc = $img;\n }\n }\n }\n }\n } ?>\n <div class=\"post_content\">\n <img src=\"<?php echo $imgsrc; $imgsrc = ''; ?>\n <a href=\"<?php the_permalink() ?>\" class=\"slide-link\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n <p class=\"sc-desc\"> <?php the_excerpt(); ?></p>\n </div>\n <?php } endwhile; ?> \n</code></pre>\n\n<p>In this code, we check if the post has thumbnail. If not, then proceed to get the children. Then again we check if the image has been retrieved. If it hasn't then we proceed to next method. Then we check again, and so on.</p>\n\n<p>At the end, if none of the method works, we simply return a <code>png</code> image and end the <code>if()</code>.</p>\n\n<p><strong>FYI:</strong> This is how <code>elseif</code> works:</p>\n\n<p><code>if ( //First condition ) {\n // check if the first condition is true, and do stuff\n} elseif ( //Second condition ) {\n //Check second condition too, and do some more stuff, no matter what was the result of the first condition and stuffs\n}</code></p>\n\n<p><strong>PS:</strong> I didn't validate the WordPress syntax. I just updated the <code>if()</code> structure for you.</p>\n\n<p><strong>PS2:</strong> You can also just use <code>if()</code> after <code>if()</code>, row after row. That can also be a solution, like the following:</p>\n\n<p><code>if ( //First ) {\n // First stuff\n} else {\n If ( //Second ) //Some code here;\n if ( //Third ) //Some more code;\n if ( //4th ) //Some extra code;\n}</code></p>\n\n<p>Choose based on your needs and style.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
]
| I'm trying to get a thumbnail for my post. Like if the first custom meta box doesn't have any `value/content`, should use `}else if ($img =get_post_custom_values('backdrop_img')) { $imgsrc = $img[0]; }` (which is the 2nd metabox) then 3rd, `else if` it also doesn't have any `content/value` just use an image from my theme directory.
But my problem is, it only works on the first meta box, which is:
```
if($img = get_post_custom_values('featured_img')){ $imgsrc = $img[0];
```
after that line the codes doesn't work and won't get values from 2nd custom meta box or use the defaul image if nothing from the conditions work.
I'm new to php and stil learning so i'm still confused. I'd appreciate any help.
So here's my code so far.
UPDATED: with the entire test code of the loop.
```
<?php $year = date ("Y"); query_posts(array(get_option('year') => $year, 'posts_per_page' => 5, 'showposts' => 5)); ?>
<?php while (have_posts()) : the_post(); ?>
<?php if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'medium');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
if($img = get_post_custom_values('featured_img')){
$imgsrc = $img[0];
}elseif($img = get_post_custom_values('backdrop_img')){
$imgsrc = $img;
} else {
$img = get_template_directory_uri().'/movies/no_img.png';
$imgsrc = $img;
}
} ?>
<div class="post_content">
<img src="<?php echo $imgsrc; $imgsrc = ''; ?>
<a href="<?php the_permalink() ?>" class="slide-link" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<p class="sc-desc"> <?php the_excerpt(); ?></p>
</div>
<?php } endwhile; ?>
``` | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,135 | <p>I am using the loop in my custom page template as you can see in my code. Only 2 posts must be shown and for the rest I should be able to have pagination.</p>
<pre><code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(
array (
'posts_per_page' => 2,
'post_type' => 'post',
'category_name' => 'news',
'category' => 1,
'paged' => $paged )
);
// The Loop
while ( have_posts() ) : the_post();?>
<div class="news-page-content-wrapper">
<div class="news-page-content">
<h1><a class="read-more"href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
<figure><?php the_post_thumbnail(); ?></figure>
<p><?php echo get_the_excerpt();?></p>
<a href="<?php the_permalink(); ?>">Read More&raquo</a>
</div>
</div>
<?endwhile;
// Reset Query
wp_reset_query();
?>
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
</code></pre>
<p>How can I have pagination using the loop with category ID?</p>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the default first\n $img = get_template_directory_uri() . '/movie/no_img.png';\n $imgsrc = $img;\n\n if (has_post_thumbnail()) {\n $imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');\n $imgsrc = $imgsrc[0];\n } elseif ($postimages = get_children(\"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\")) {\n foreach ($postimages as $postimage) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n } elseif (preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match) != FALSE) {\n $imgsrc = $match[1];\n } else {\n $img = get_post_custom_values('featured_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } else {\n $img = get_post_custom_values('backdrop_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } \n\n }\n }\n //use it after all the logic\n echo $imgsrc;\n\n ?>\n</code></pre>\n\n<p>by the way if this is in the loop you can just use <code>get_the_ID</code></p>\n"
},
{
"answer_id": 257126,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>i think you have wrong this else if not right elseif is right so your else part is not execute.\ndocument link : <code>http://php.net/manual/en/control-structures.elseif.php</code></p>\n\n<p>your code like this : </p>\n\n<pre><code>else if ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>Replace with :</p>\n\n<pre><code>elseif ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>I hope it's helpful.</p>\n"
},
{
"answer_id": 257131,
"author": "Archangel17",
"author_id": 110405,
"author_profile": "https://wordpress.stackexchange.com/users/110405",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing <code>[0]</code> in <code>$imgsrc = $img[0];</code> and using <code>custom_get_meta()</code></p>\n\n<p>like: </p>\n\n<p><code>$img = post_movie_get_meta('featured_img')</code></p>\n\n<p>and:</p>\n\n<p><code>$img = post_movie_get_meta('backdrop_img')</code></p>\n"
},
{
"answer_id": 257161,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>This is not how you should use <code>elseif</code>. Note that the following <code>elseif</code> conditions will run, not matter the result of your initial <code>if()</code>. You should use nested <code>if()</code> instead.</p>\n\n<p>Take a look at this:</p>\n\n<pre><code> <?php \n $year = date (\"Y\");\n query_posts(\n array(\n get_option('year') => $year,\n 'posts_per_page' => 5,\n 'showposts' => 5)\n );\n while ( have_posts() ) : the_post(); \n if ( has_post_thumbnail() ) {\n $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );\n $imgsrc = $imgsrc[0];\n } else {\n $postimages = get_children( \"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\" );\n foreach( $postimages as $postimage ) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n if ( !$imgsrc ) {\n preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match);\n $imgsrc = $match[1];\n if (!$imgsrc){\n $img = get_post_custom_values('featured_img');\n $imgsrc = $img[0];\n if (!$imgsrc){\n $img = get_post_custom_values('backdrop_img');\n $imgsrc = $img;\n if (!$imgsrc){\n $img = get_template_directory_uri().'/movies/no_img.png';\n $imgsrc = $img;\n }\n }\n }\n }\n } ?>\n <div class=\"post_content\">\n <img src=\"<?php echo $imgsrc; $imgsrc = ''; ?>\n <a href=\"<?php the_permalink() ?>\" class=\"slide-link\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n <p class=\"sc-desc\"> <?php the_excerpt(); ?></p>\n </div>\n <?php } endwhile; ?> \n</code></pre>\n\n<p>In this code, we check if the post has thumbnail. If not, then proceed to get the children. Then again we check if the image has been retrieved. If it hasn't then we proceed to next method. Then we check again, and so on.</p>\n\n<p>At the end, if none of the method works, we simply return a <code>png</code> image and end the <code>if()</code>.</p>\n\n<p><strong>FYI:</strong> This is how <code>elseif</code> works:</p>\n\n<p><code>if ( //First condition ) {\n // check if the first condition is true, and do stuff\n} elseif ( //Second condition ) {\n //Check second condition too, and do some more stuff, no matter what was the result of the first condition and stuffs\n}</code></p>\n\n<p><strong>PS:</strong> I didn't validate the WordPress syntax. I just updated the <code>if()</code> structure for you.</p>\n\n<p><strong>PS2:</strong> You can also just use <code>if()</code> after <code>if()</code>, row after row. That can also be a solution, like the following:</p>\n\n<p><code>if ( //First ) {\n // First stuff\n} else {\n If ( //Second ) //Some code here;\n if ( //Third ) //Some more code;\n if ( //4th ) //Some extra code;\n}</code></p>\n\n<p>Choose based on your needs and style.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
]
| I am using the loop in my custom page template as you can see in my code. Only 2 posts must be shown and for the rest I should be able to have pagination.
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(
array (
'posts_per_page' => 2,
'post_type' => 'post',
'category_name' => 'news',
'category' => 1,
'paged' => $paged )
);
// The Loop
while ( have_posts() ) : the_post();?>
<div class="news-page-content-wrapper">
<div class="news-page-content">
<h1><a class="read-more"href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
<figure><?php the_post_thumbnail(); ?></figure>
<p><?php echo get_the_excerpt();?></p>
<a href="<?php the_permalink(); ?>">Read More»</a>
</div>
</div>
<?endwhile;
// Reset Query
wp_reset_query();
?>
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
```
How can I have pagination using the loop with category ID? | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,153 | <p>I'm at a loss.. </p>
<p>I wanna check the current users post count. If the post count is 1, the user should be redirected. I have tested the following code:</p>
<pre><code>add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
$current_user = wp_get_current_user();
if (empty($the_user_id)) {
$the_user_id = $current_user->ID;
}
$user_post_count = count_user_posts( $the_user_id );
if ( is_page('butiktest') && $user_post_count == 1 ) {
wp_redirect( 'enhytte', 301 );
exit;
}
}
</code></pre>
<p>However, the above code will redirect no matter the amount of posts.</p>
<p>What am I doing wrong?</p>
<p>EDIT: After pointing out my syntax error was a missing "=", it is still not working.</p>
<p>EDIT 2: The code is in theory working, however, once a post is added, the <code>user_post_count</code> is not updated, and stays at the previous value. </p>
<p>EDIT3: count_user_posts only count published posts, how do I check for 'pending' and 'draft'?</p>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the default first\n $img = get_template_directory_uri() . '/movie/no_img.png';\n $imgsrc = $img;\n\n if (has_post_thumbnail()) {\n $imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');\n $imgsrc = $imgsrc[0];\n } elseif ($postimages = get_children(\"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\")) {\n foreach ($postimages as $postimage) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n } elseif (preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match) != FALSE) {\n $imgsrc = $match[1];\n } else {\n $img = get_post_custom_values('featured_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } else {\n $img = get_post_custom_values('backdrop_img', get_the_ID());\n if (isset($img)) {\n $imgsrc = $img[0];\n } \n\n }\n }\n //use it after all the logic\n echo $imgsrc;\n\n ?>\n</code></pre>\n\n<p>by the way if this is in the loop you can just use <code>get_the_ID</code></p>\n"
},
{
"answer_id": 257126,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>i think you have wrong this else if not right elseif is right so your else part is not execute.\ndocument link : <code>http://php.net/manual/en/control-structures.elseif.php</code></p>\n\n<p>your code like this : </p>\n\n<pre><code>else if ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>Replace with :</p>\n\n<pre><code>elseif ($img =get_post_custom_values('backdrop_img')) {\n</code></pre>\n\n<p>I hope it's helpful.</p>\n"
},
{
"answer_id": 257131,
"author": "Archangel17",
"author_id": 110405,
"author_profile": "https://wordpress.stackexchange.com/users/110405",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing <code>[0]</code> in <code>$imgsrc = $img[0];</code> and using <code>custom_get_meta()</code></p>\n\n<p>like: </p>\n\n<p><code>$img = post_movie_get_meta('featured_img')</code></p>\n\n<p>and:</p>\n\n<p><code>$img = post_movie_get_meta('backdrop_img')</code></p>\n"
},
{
"answer_id": 257161,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>This is not how you should use <code>elseif</code>. Note that the following <code>elseif</code> conditions will run, not matter the result of your initial <code>if()</code>. You should use nested <code>if()</code> instead.</p>\n\n<p>Take a look at this:</p>\n\n<pre><code> <?php \n $year = date (\"Y\");\n query_posts(\n array(\n get_option('year') => $year,\n 'posts_per_page' => 5,\n 'showposts' => 5)\n );\n while ( have_posts() ) : the_post(); \n if ( has_post_thumbnail() ) {\n $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );\n $imgsrc = $imgsrc[0];\n } else {\n $postimages = get_children( \"post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0\" );\n foreach( $postimages as $postimage ) {\n $imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');\n $imgsrc = $imgsrc[0];\n }\n if ( !$imgsrc ) {\n preg_match('/<img [^>]*src=[\"|\\']([^\"|\\']+)/i', get_the_content(), $match);\n $imgsrc = $match[1];\n if (!$imgsrc){\n $img = get_post_custom_values('featured_img');\n $imgsrc = $img[0];\n if (!$imgsrc){\n $img = get_post_custom_values('backdrop_img');\n $imgsrc = $img;\n if (!$imgsrc){\n $img = get_template_directory_uri().'/movies/no_img.png';\n $imgsrc = $img;\n }\n }\n }\n }\n } ?>\n <div class=\"post_content\">\n <img src=\"<?php echo $imgsrc; $imgsrc = ''; ?>\n <a href=\"<?php the_permalink() ?>\" class=\"slide-link\" title=\"<?php the_title(); ?>\"><?php the_title(); ?></a>\n <p class=\"sc-desc\"> <?php the_excerpt(); ?></p>\n </div>\n <?php } endwhile; ?> \n</code></pre>\n\n<p>In this code, we check if the post has thumbnail. If not, then proceed to get the children. Then again we check if the image has been retrieved. If it hasn't then we proceed to next method. Then we check again, and so on.</p>\n\n<p>At the end, if none of the method works, we simply return a <code>png</code> image and end the <code>if()</code>.</p>\n\n<p><strong>FYI:</strong> This is how <code>elseif</code> works:</p>\n\n<p><code>if ( //First condition ) {\n // check if the first condition is true, and do stuff\n} elseif ( //Second condition ) {\n //Check second condition too, and do some more stuff, no matter what was the result of the first condition and stuffs\n}</code></p>\n\n<p><strong>PS:</strong> I didn't validate the WordPress syntax. I just updated the <code>if()</code> structure for you.</p>\n\n<p><strong>PS2:</strong> You can also just use <code>if()</code> after <code>if()</code>, row after row. That can also be a solution, like the following:</p>\n\n<p><code>if ( //First ) {\n // First stuff\n} else {\n If ( //Second ) //Some code here;\n if ( //Third ) //Some more code;\n if ( //4th ) //Some extra code;\n}</code></p>\n\n<p>Choose based on your needs and style.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112830/"
]
| I'm at a loss..
I wanna check the current users post count. If the post count is 1, the user should be redirected. I have tested the following code:
```
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
$current_user = wp_get_current_user();
if (empty($the_user_id)) {
$the_user_id = $current_user->ID;
}
$user_post_count = count_user_posts( $the_user_id );
if ( is_page('butiktest') && $user_post_count == 1 ) {
wp_redirect( 'enhytte', 301 );
exit;
}
}
```
However, the above code will redirect no matter the amount of posts.
What am I doing wrong?
EDIT: After pointing out my syntax error was a missing "=", it is still not working.
EDIT 2: The code is in theory working, however, once a post is added, the `user_post_count` is not updated, and stays at the previous value.
EDIT3: count\_user\_posts only count published posts, how do I check for 'pending' and 'draft'? | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,189 | <p>So right now the site automatically creates pages when a post is updated. I want this page to include an audio playlist. So what I do, is simply add the shortcode: <code>[playlist]</code>.
Then, when the audio files are attached to the page, the playlist automatically generates.</p>
<p>I can confirm that this method works with specified IDs.</p>
<p><strong>The problem is</strong>, that 3 different pages are made, and I need the audio to be attached to all three pages. So my solution is that I make a another page, set the audio files as children to that page, and make the original 3 pages children of the new page. Then I could use the <code>[playlist]</code> shortcode, but tell it to get the id from the parent page.</p>
<p><strong>Example:</strong></p>
<pre><code>[playlist id="<?php get_parent_id ?>"]
</code></pre>
<p>or something like this.</p>
<p>The problem is that I cannot get the parent id. I've tried multiple different lines of code and nothing will work. The playlist just gets the default 0 ID, which it does when <code>id=""</code> is left blank.</p>
<p>This is all going into the <code>functions.php</code> file in my theme's directory.</p>
<p>--</p>
<p>Maybe there is a better way to do this, thusfar, this seems like the simplest solution, if only I can get the direct parent ID. It must exist.</p>
| [
{
"answer_id": 276771,
"author": "Shahzaib Khan",
"author_id": 125791,
"author_profile": "https://wordpress.stackexchange.com/users/125791",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways you can do this:</p>\n\n<ul>\n<li>Manual</li>\n<li>Using plugin</li>\n</ul>\n\n<p>For manual, it's a little more lengthy process, you need to download complete files from one server and upload it to another. Do some changes to the backup DB i.e replacing urls and then uploading the DB file as well.</p>\n\n<p>Other way, which is far more better is to use the plugin called as \"All in one Migration\". Here is the link which can guide you on the complete process:</p>\n\n<p><a href=\"https://makersbyte.com/easily-export-import-wordpress-sites/\" rel=\"nofollow noreferrer\">https://makersbyte.com/easily-export-import-wordpress-sites/</a></p>\n"
},
{
"answer_id": 307535,
"author": "Muhammad Tahseen ur Rehman",
"author_id": 146048,
"author_profile": "https://wordpress.stackexchange.com/users/146048",
"pm_score": 4,
"selected": false,
"text": "<p>Use <strong>Export Featured Images</strong> plugin that let you export Featured images from posts or custom post types into a WordPress xml so you can import them in other sites using the WordPress importer tool.</p>\n\n<blockquote>\n <p><a href=\"https://wordpress.org/plugins/export-featured-images/#description\" rel=\"noreferrer\">https://wordpress.org/plugins/export-featured-images/#description</a></p>\n</blockquote>\n\n<p><strong>How to use??</strong></p>\n\n<ol>\n<li>First, import your posts to the new site.</li>\n<li>Use this plugin in your old site and go to under <strong>tools > Export Featured Images</strong> and select post types.\nThen you will get a <strong>.xml file</strong>.</li>\n<li>In your new site go to <strong>Tool</strong> and select <strong>wordpress import</strong>. Then select the <strong>.xml file</strong> which you downloaded in the previous step.</li>\n</ol>\n\n<p>That’s all.. Your posts are mapped with featured images. Enjoy!</p>\n"
},
{
"answer_id": 315208,
"author": "Dvaeer",
"author_id": 92868,
"author_profile": "https://wordpress.stackexchange.com/users/92868",
"pm_score": 5,
"selected": false,
"text": "<h1>Why images don't get imported</h1>\n\n<p>It's the export step that causes the issue here with image attachments. WordPress’ export function doesn’t include the “attachment” post type unless you select the “All content” export option. But if you only want to import and export your posts from one site to another, you lose your attachments. There is more information about the why of this <a href=\"https://mor10.com/wordpress-importer-not-importing-attachments-try-exporting-all-statuses/#comment-1151023\" rel=\"noreferrer\">here</a>.</p>\n\n<h1>How to get images into your new website anyway</h1>\n\n<p>So if you're only exporting and importing posts, one option is to move your images manually. But that's potentially a lot of work, especially on larger sites. The other option is to import you posts without the images, and then use the <a href=\"https://wordpress.org/plugins/auto-upload-images/\" rel=\"noreferrer\">Auto Upload Images plugin</a> to add the images afterwards. This plugin does several things: </p>\n\n<ul>\n<li>It looks for image URLs in your posts (imported posts do still have image URLs in them, but they point to the site the content was exported from);</li>\n<li>It then gets those external images and uploads them to the local WordPress uploads directory and adds the images to the media library;</li>\n<li>And finally, it replaces the old image URLs with new URLs.</li>\n</ul>\n\n<p>The process is semi-automatic and relatively quick. You can uninstall the plugin again when you're done, so you're not left with an extra plugin on your website. Using the plugin for this purpose isn't explicitly documented in the plugin's documentation, so here is a step-by-step guide.</p>\n\n<h2>Step by step: Importing posts and images from one website into another with the WordPress Importer and Auto Upload Images plugin</h2>\n\n<p><strong>Step 1: Prepare your export file on the old site</strong><br />\nOn your old website go to 'Tools > Export' and export your posts only.</p>\n\n<p><strong>Step 2: Import your posts into the new site</strong><br />\nOn your new website go to 'Tools > Import' and import the posts you exported. The importer has an option to download and import file attachments, but this won't work if you're not migrating all content, so you can ignore this.</p>\n\n<p><strong>Step 3: Install and activate the Auto Upload Images plugin</strong><br />\nIt installs as any other plugin in the WordPress repository. Once activated the plugin adds a settings page under 'Settings > Auto Upload Images', but in my experience you can leave these to their defaults.</p>\n\n<p><strong>Step 4: Get the image from your old site into your new site</strong><br />\nAt the time of writing the plugin has no option to automatically go through your posts and bulk upload plus update all the images. Instead, it updates each post individually when you save it. If you have many posts this is a lot of work, but there is a little trick. You can go to your posts overview screen and <em>bulk update your posts</em>. There is a little more information on this <a href=\"https://wordpress.org/support/topic/why-no-option-to-run-this-in-bulk-on-all-existing-posts/\" rel=\"noreferrer\">here</a> (useful note on multisite). </p>\n\n<p>Essentially, you select multiple posts and then under 'bulk actions' choose 'edit' and press the 'apply' button. Then, without making any adjustments, click the 'Update' button. Depending on your server you may get a timeout as the process runs, so it's a good idea to do this maybe 20 to 50 posts at a time. </p>\n\n<p><a href=\"https://i.stack.imgur.com/DKzjs.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DKzjs.png\" alt=\"Bulk-updating posts\"></a></p>\n\n<p><strong>Step 5: Check your posts and deactivate/uninstall the plugin</strong><br />\nWhen all is done you can check your posts and confirm they now reference local images. You then no longer need the plugin and you can safely deactivate and delete it.</p>\n\n<h1>Final thoughts</h1>\n\n<p>Probably a good idea to make a backup of your new site first (at least of your site's database). </p>\n\n<p>At the time of writing the Auto Upload Images plugin hasn't been updated for quite some time, but on testing it worked fine. </p>\n\n<p>With this method all images in posts get imported, not just featured images.</p>\n"
},
{
"answer_id": 324242,
"author": "Manish Kumar",
"author_id": 157979,
"author_profile": "https://wordpress.stackexchange.com/users/157979",
"pm_score": 2,
"selected": false,
"text": "<p>I am the best person to answer this question as I was facing the same issue while importing. The problem is not actually in importing.</p>\n\n<p><br> It is in exporting. When you export all content then you import with attachments that XML file all your images will be download but when you export selected posts then import with attachments then only posts get imported. \nSo to fix this there is a plugin which exports the right XML file that it does same like export all content XML file.<br></p>\n\n<p><strong>So here is the plugin <a href=\"https://wordpress.org/plugins/demomentsomtres-wp-export\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/demomentsomtres-wp-export</a></strong></p>\n\n<p>This will create a new export option just like default WordPress export GUI, but with advanced features so that when you import that XML file your media will be imported while importing that XML file(from default server to your local server). You don't need to install it in the Wordpress where you importing media, It just needs to be installed on the exporting server WordPress.</p>\n"
},
{
"answer_id": 345484,
"author": "Petia Koleva",
"author_id": 173801,
"author_profile": "https://wordpress.stackexchange.com/users/173801",
"pm_score": 2,
"selected": false,
"text": "<p>That did the trick for me. All other options didn't work, but that plugin finally did what I needed!</p>\n\n<p>I had to export real estate properties from one site to another. Each property has a lot of images. This plugin <a href=\"https://wordpress.org/plugins/demomentsomtres-wp-export\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/demomentsomtres-wp-export</a> did exactly what I needed - downloaded and uploaded all the images from the first site to the second. </p>\n"
},
{
"answer_id": 372361,
"author": "Subtopic",
"author_id": 182626,
"author_profile": "https://wordpress.stackexchange.com/users/182626",
"pm_score": 0,
"selected": false,
"text": "<p>I just found out how to do this today, and answered this question with a great guide with photos on how to use the export and import tools in WordPress to transfer photos to a new site to be used in posts and pages. This is done by editing the xml files to show the correctly transferred image URLs.</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/117344/failed-to-import-media/372304#372304\">Failed to import Media</a></p>\n"
},
{
"answer_id": 378504,
"author": "doremember",
"author_id": 117074,
"author_profile": "https://wordpress.stackexchange.com/users/117074",
"pm_score": 2,
"selected": false,
"text": "<p>I´ve tried mentioned plugins and "DeMomentSomTres Export" - worked on featured images + some but not all regular images and "Auto Upload Images" - worked on all regular images but not on featured images. If you combine the two of them problem would be solved but not ideal to have two plugins for the same purpose. Instead i found another plugin that worked like a charm:</p>\n<p><strong>"Export Media with Selected Content"</strong></p>\n<p>Only needed on exporting site, the importing site can use the regular importer. Worked for me and ALL images were included.</p>\n"
},
{
"answer_id": 395103,
"author": "Vishal",
"author_id": 123355,
"author_profile": "https://wordpress.stackexchange.com/users/123355",
"pm_score": 0,
"selected": false,
"text": "<p>there is a very simple way to do it. When you are export your posts from Wordpress via <strong>WORDPRESS IMPORTER</strong> plugin.</p>\n<hr />\n<p>steps</p>\n<hr />\n<p>1- download XML Posts File.</p>\n<p>2- Edit your XML posts file, now replace your old website url's with new website url's in editor(notepad or any other).</p>\n<p>3-make sure your old url is replaced with new in downloaded XML file, save it.</p>\n<p>4- now import this edited file in your new Wordpress website.</p>\n<hr />\n<p>that's it.</p>\n<p>all done</p>\n<p>you can easily did this with replacing url in XML file.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113483/"
]
| So right now the site automatically creates pages when a post is updated. I want this page to include an audio playlist. So what I do, is simply add the shortcode: `[playlist]`.
Then, when the audio files are attached to the page, the playlist automatically generates.
I can confirm that this method works with specified IDs.
**The problem is**, that 3 different pages are made, and I need the audio to be attached to all three pages. So my solution is that I make a another page, set the audio files as children to that page, and make the original 3 pages children of the new page. Then I could use the `[playlist]` shortcode, but tell it to get the id from the parent page.
**Example:**
```
[playlist id="<?php get_parent_id ?>"]
```
or something like this.
The problem is that I cannot get the parent id. I've tried multiple different lines of code and nothing will work. The playlist just gets the default 0 ID, which it does when `id=""` is left blank.
This is all going into the `functions.php` file in my theme's directory.
--
Maybe there is a better way to do this, thusfar, this seems like the simplest solution, if only I can get the direct parent ID. It must exist. | Why images don't get imported
=============================
It's the export step that causes the issue here with image attachments. WordPress’ export function doesn’t include the “attachment” post type unless you select the “All content” export option. But if you only want to import and export your posts from one site to another, you lose your attachments. There is more information about the why of this [here](https://mor10.com/wordpress-importer-not-importing-attachments-try-exporting-all-statuses/#comment-1151023).
How to get images into your new website anyway
==============================================
So if you're only exporting and importing posts, one option is to move your images manually. But that's potentially a lot of work, especially on larger sites. The other option is to import you posts without the images, and then use the [Auto Upload Images plugin](https://wordpress.org/plugins/auto-upload-images/) to add the images afterwards. This plugin does several things:
* It looks for image URLs in your posts (imported posts do still have image URLs in them, but they point to the site the content was exported from);
* It then gets those external images and uploads them to the local WordPress uploads directory and adds the images to the media library;
* And finally, it replaces the old image URLs with new URLs.
The process is semi-automatic and relatively quick. You can uninstall the plugin again when you're done, so you're not left with an extra plugin on your website. Using the plugin for this purpose isn't explicitly documented in the plugin's documentation, so here is a step-by-step guide.
Step by step: Importing posts and images from one website into another with the WordPress Importer and Auto Upload Images plugin
--------------------------------------------------------------------------------------------------------------------------------
**Step 1: Prepare your export file on the old site**
On your old website go to 'Tools > Export' and export your posts only.
**Step 2: Import your posts into the new site**
On your new website go to 'Tools > Import' and import the posts you exported. The importer has an option to download and import file attachments, but this won't work if you're not migrating all content, so you can ignore this.
**Step 3: Install and activate the Auto Upload Images plugin**
It installs as any other plugin in the WordPress repository. Once activated the plugin adds a settings page under 'Settings > Auto Upload Images', but in my experience you can leave these to their defaults.
**Step 4: Get the image from your old site into your new site**
At the time of writing the plugin has no option to automatically go through your posts and bulk upload plus update all the images. Instead, it updates each post individually when you save it. If you have many posts this is a lot of work, but there is a little trick. You can go to your posts overview screen and *bulk update your posts*. There is a little more information on this [here](https://wordpress.org/support/topic/why-no-option-to-run-this-in-bulk-on-all-existing-posts/) (useful note on multisite).
Essentially, you select multiple posts and then under 'bulk actions' choose 'edit' and press the 'apply' button. Then, without making any adjustments, click the 'Update' button. Depending on your server you may get a timeout as the process runs, so it's a good idea to do this maybe 20 to 50 posts at a time.
[](https://i.stack.imgur.com/DKzjs.png)
**Step 5: Check your posts and deactivate/uninstall the plugin**
When all is done you can check your posts and confirm they now reference local images. You then no longer need the plugin and you can safely deactivate and delete it.
Final thoughts
==============
Probably a good idea to make a backup of your new site first (at least of your site's database).
At the time of writing the Auto Upload Images plugin hasn't been updated for quite some time, but on testing it worked fine.
With this method all images in posts get imported, not just featured images. |
257,227 | <p>I created a custom post type for WP, that should just be visitable for user that have a custom capability <code>read_cpt</code>. Within templates and <code>pre_get_posts</code> I can run checks to include or exclude the CPT by using <code>current_user_can()</code>.</p>
<p>I don't want the CPT, not even the endpoint, to show up within the REST API, to keep it top secret, as long as a user doesn't have the custom capability.</p>
<p>The only way I could figure out to hide the endpoints in the API to run this code.</p>
<p>Register post type for "classic" WP:</p>
<pre><code>function add_post_type() {
$args = array(
[...]
'public' => false,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_in_rest' => false,
);
register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type', 0 );
</code></pre>
<p>and separately add it to the REST API:</p>
<pre><code>add_action( 'init', 'cpt_rest_support', 25 );
function cpt_rest_support() {
global $wp_post_types;
if ( current_user_can( 'read_addresses' ) ) {
//be sure to set this to the name of your post type!
$post_type_name = 'address';
if( isset( $wp_post_types[ 'cpt' ] ) ) {
$wp_post_types[ 'cpt' ]->show_in_rest = true;
}
}
}
</code></pre>
<p>By creating a custom <code>WP_REST_Posts_Controller</code> class I couldn't find a way to hide the endpoint by modifying any of the <code>*_permissions_check</code></p>
<p>Is there something like a "show_in_rest_permition_check" argument for <code>register_post_type()</code> or is the described way the only method?</p>
| [
{
"answer_id": 257250,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>The REST API has no parameters, options to solve this - in my opinion. But you should register only if the users have the capability in his role, like the follow example.</p>\n<pre><code>add_action( 'rest_api_init', function() {\n\n // Exit, if the logged in user have not enough rights.\n if ( ! current_user_can( 'edit_posts' ) ) {\n return;\n }\n\n // Register Meta Data.\n register_meta( 'post', 'foo', array(\n 'show_in_rest' => true,\n ));\n});\n</code></pre>\n<p>That's fire the custom data in the REST API only, if the user have enough rights, capabilities in his role. My <code>register_meta()</code> is only an example, that should also work with your additional parameter for <code>register_post_type</code>, like <code>$wp_post_types[ 'cpt' ]->show_in_rest = true;</code>.</p>\n"
},
{
"answer_id": 352369,
"author": "Walf",
"author_id": 27856,
"author_profile": "https://wordpress.stackexchange.com/users/27856",
"pm_score": 0,
"selected": false,
"text": "<p>Don't rely solely on hiding it.</p>\n\n<p>Instead, return an error in the handler:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if (!current_user_can('read_addresses')) {\n return new WP_REST_Response('restricted', 403);\n}\n</code></pre>\n\n<p>To hide it as well, filter the content of the hooks <code>rest_index</code> and <code>rest_namespace_index</code>.</p>\n"
},
{
"answer_id": 352409,
"author": "Dino Morrison",
"author_id": 154353,
"author_profile": "https://wordpress.stackexchange.com/users/154353",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\">register_rest_route()</a> function.</p>\n\n<pre><code>if( current_user_can( 'read_addresses' ) ) {\n register_rest_route( 'namespace/v1', 'cpt', array(\n 'methods' => array( 'GET' ),\n 'callback' => 'callback_function',\n 'permission_callback' => 'permission_callback_function'\n ) );\n}\n</code></pre>\n\n<p>Your <code>callback_function</code> would handle the request and return the response. The <code>permissions_callback_function</code> would check the user permissions and return an error if the user does not have the specified capabilities. In this case the permissions callback is probably not necessary, but it wouldn't hurt to have it in place just in case.</p>\n"
},
{
"answer_id": 395989,
"author": "Luismi",
"author_id": 105989,
"author_profile": "https://wordpress.stackexchange.com/users/105989",
"pm_score": 0,
"selected": false,
"text": "<p>Old question but this worked for me following @Drivingralle requirements. You could use <code>current_user_can()</code> as a boolean switch to modify <code>show_in_rest</code> parameter behaviour:</p>\n<pre><code>function add_post_type() {\n\n $show_in_rest = current_user_can( 'read_cpt' ); //this will return true or false\n\n $args = array(\n [...]\n 'public' => false,\n 'has_archive' => false,\n 'exclude_from_search' => true,\n 'publicly_queryable' => false,\n 'show_in_rest' => $show_in_rest, //bool switch from current_user_can()\n );\n register_post_type( 'cpt', $args );\n}\nadd_action( 'init', 'add_post_type' );\n</code></pre>\n<p>This way the custom post type is only shown in rest for users with the required capability.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257227",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45303/"
]
| I created a custom post type for WP, that should just be visitable for user that have a custom capability `read_cpt`. Within templates and `pre_get_posts` I can run checks to include or exclude the CPT by using `current_user_can()`.
I don't want the CPT, not even the endpoint, to show up within the REST API, to keep it top secret, as long as a user doesn't have the custom capability.
The only way I could figure out to hide the endpoints in the API to run this code.
Register post type for "classic" WP:
```
function add_post_type() {
$args = array(
[...]
'public' => false,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_in_rest' => false,
);
register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type', 0 );
```
and separately add it to the REST API:
```
add_action( 'init', 'cpt_rest_support', 25 );
function cpt_rest_support() {
global $wp_post_types;
if ( current_user_can( 'read_addresses' ) ) {
//be sure to set this to the name of your post type!
$post_type_name = 'address';
if( isset( $wp_post_types[ 'cpt' ] ) ) {
$wp_post_types[ 'cpt' ]->show_in_rest = true;
}
}
}
```
By creating a custom `WP_REST_Posts_Controller` class I couldn't find a way to hide the endpoint by modifying any of the `*_permissions_check`
Is there something like a "show\_in\_rest\_permition\_check" argument for `register_post_type()` or is the described way the only method? | The REST API has no parameters, options to solve this - in my opinion. But you should register only if the users have the capability in his role, like the follow example.
```
add_action( 'rest_api_init', function() {
// Exit, if the logged in user have not enough rights.
if ( ! current_user_can( 'edit_posts' ) ) {
return;
}
// Register Meta Data.
register_meta( 'post', 'foo', array(
'show_in_rest' => true,
));
});
```
That's fire the custom data in the REST API only, if the user have enough rights, capabilities in his role. My `register_meta()` is only an example, that should also work with your additional parameter for `register_post_type`, like `$wp_post_types[ 'cpt' ]->show_in_rest = true;`. |
257,235 | <p>After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript.
So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.</p>
<p>Can anyone suggest what I can do to resolve this issue please?</p>
<p>The site is <a href="http://www.stewartandsonsroofingliverpool.co.uk/" rel="nofollow noreferrer">http://www.stewartandsonsroofingliverpool.co.uk/</a></p>
<p>Thanks in advance</p>
| [
{
"answer_id": 257238,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your <code>functions.php</code> to load your scripts asynchronously.</p>\n\n<p>This can get you started, </p>\n\n<blockquote>\n <p>Warning</p>\n</blockquote>\n\n<p>loading JavaScript asynchronously will cause several issues with dependencies:</p>\n\n<pre><code>/*function to add async to all scripts*/\nfunction js_async_attr($tag){\n //Add async to all scripts tags\n return str_replace( ' src', ' async=\"async\" src', $tag );\n}\nadd_filter( 'script_loader_tag', 'js_async_attr', 10 );\n</code></pre>\n\n<p>so you have to check your JS code and update it.</p>\n"
},
{
"answer_id": 257274,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 1,
"selected": false,
"text": "<h1>Use <code>defer</code> attribute</h1>\n\n<p>Instead of converting all script to <code>async</code> as <a href=\"https://wordpress.stackexchange.com/a/257238/111485\">this answer suggested</a>, it's better to use <code>defer</code>. That way, you'll not have dependency errors.</p>\n\n<p>For example, you use a custom script and that script depends on <code>jQuery</code>. Since <code>jQuery</code> is more likely to be bigger than your custom script, it'll probably end loading before <code>jQuery</code>, so your CODE will behave unpredictably.</p>\n\n<p>Instead you can use the following CODE to make sure dependency works:</p>\n\n<pre><code>function js_defer_attr( $tag ){\n // add defer to all scripts tags\n return str_replace( ' src', ' defer=\"defer\" src', $tag );\n}\nadd_filter( 'script_loader_tag', 'js_defer_attr', 10 );\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/5250412\">Here's more</a> about the <code>defer</code> attribute.</p>\n\n<h1>Alternative: place script to footer</h1>\n\n<p>It's also possible to replace all scripts to footer. Use the following CODE (instead of the above) to place all scripts in the footer:</p>\n\n<pre><code>function move_scripts_to_footer() {\n remove_action( 'wp_head', 'wp_print_scripts' );\n remove_action( 'wp_head', 'wp_print_head_scripts', 9 );\n remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );\n add_action( 'wp_footer', 'wp_print_scripts', 5 );\n add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );\n add_action( 'wp_footer', 'wp_print_head_scripts', 5 );\n}\nadd_action( 'wp_head', 'move_scripts_to_footer', -1 );\n</code></pre>\n"
},
{
"answer_id": 323026,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>You can eliminate render blocking JavaScript very easily by using different plugins, like <a href=\"https://wordpress.org/plugins/autoptimize/\" rel=\"nofollow noreferrer\">Autoptimize</a>. Follow these steps:</p>\n\n<ol>\n<li>Install and activate Autoptimize.</li>\n<li>Head to <strong>Settings > Autoptimize</strong>.</li>\n<li>Check the boxes beside \"<strong>Optimize JavaScript Code?</strong>\" and \"<strong>Optimize\nJavaScript Code?</strong>\" options.</li>\n<li>Click on <strong>Save Changes</strong> button.</li>\n</ol>\n\n<p>You can also use W3 Total Cache plugin to solve the issue. You will find the steps for applying it <a href=\"https://hostadvice.com/how-to/how-to-fix-render-blocking-javascript-and-css-of-your-wordpress-website/\" rel=\"nofollow noreferrer\">right here</a>.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/46039/"
]
| After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript.
So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.
Can anyone suggest what I can do to resolve this issue please?
The site is <http://www.stewartandsonsroofingliverpool.co.uk/>
Thanks in advance | You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your `functions.php` to load your scripts asynchronously.
This can get you started,
>
> Warning
>
>
>
loading JavaScript asynchronously will cause several issues with dependencies:
```
/*function to add async to all scripts*/
function js_async_attr($tag){
//Add async to all scripts tags
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
```
so you have to check your JS code and update it. |
257,240 | <p>I'm loading a list of products on an archive type page and creating a custom query to do so. I want to create a 'load more' functionality so that clicking the 'load more' button at the bottom of list loads the next 10 products.</p>
<p>I thought it would be as easy as using a variable to set 'posts_per_page' and simply increment it by 10 when the button is clicked. I get strange results however. This code is not the final code but just to illustrate this problem.</p>
<pre><code>if(isset( $_POST['load-next-amount'] )){
$pageamount = 10
}
else {
$pageamount = 5;
}
</code></pre>
<p>So the first time this is loaded it resolves to false because the button hasny't yet been clicked, so posts_per_page will be set to 5. Then when clicking the button, you would expect 10 to load but for some reason it continues to load 5. If however I change the code to this:</p>
<pre><code>if(isset( $_POST['load-next-amount'] )){
$pageamount = 4
}
else {
$pageamount = 5;
}
</code></pre>
<p>it will load 4. So I cannot increase the amount of posts_per_page through this variable, but I can decrease it. Strange.</p>
<p>Here is my query:</p>
<pre><code>$myArgs = array(
'category' => '',
'category_name' => '',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'include' => '',
'exclude' => '',
'meta_key' => '_price_per_1hr_lesson',
'meta_value' => '',
'post_type' => 'job_listing',
'post_mime_type' => '',
'post_parent' => '',
'post__in' => $what,
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'job_listing_region' => "'" . $city . "'",
'post_status' => 'publish',
'posts_per_page' => $pageamount,
'suppress_filters' => true
);
$myquery = new WP_Query( $myArgs );
</code></pre>
<p>UPDATE: using print_r I can see that the correct value is being assigned to the variable and that value is being correctly assigned to 'posts_per_page'. For whatever reason, it ignores it UNLESS it is LESS than the previously assigned value. For instance if I set the else statement to $pageamount = 20, the first time the page loads there will be 20, then if i click the button(sending the variable to the script which is 10) it will load 10. It will load any number of posts I hard code as long as it's less than 20. </p>
<p>Obviously there is something in WP that is setting a default or something. Still a bit of a newb to WP so I don't know. Looking at wp_config and I dont' see anything.</p>
| [
{
"answer_id": 257238,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your <code>functions.php</code> to load your scripts asynchronously.</p>\n\n<p>This can get you started, </p>\n\n<blockquote>\n <p>Warning</p>\n</blockquote>\n\n<p>loading JavaScript asynchronously will cause several issues with dependencies:</p>\n\n<pre><code>/*function to add async to all scripts*/\nfunction js_async_attr($tag){\n //Add async to all scripts tags\n return str_replace( ' src', ' async=\"async\" src', $tag );\n}\nadd_filter( 'script_loader_tag', 'js_async_attr', 10 );\n</code></pre>\n\n<p>so you have to check your JS code and update it.</p>\n"
},
{
"answer_id": 257274,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 1,
"selected": false,
"text": "<h1>Use <code>defer</code> attribute</h1>\n\n<p>Instead of converting all script to <code>async</code> as <a href=\"https://wordpress.stackexchange.com/a/257238/111485\">this answer suggested</a>, it's better to use <code>defer</code>. That way, you'll not have dependency errors.</p>\n\n<p>For example, you use a custom script and that script depends on <code>jQuery</code>. Since <code>jQuery</code> is more likely to be bigger than your custom script, it'll probably end loading before <code>jQuery</code>, so your CODE will behave unpredictably.</p>\n\n<p>Instead you can use the following CODE to make sure dependency works:</p>\n\n<pre><code>function js_defer_attr( $tag ){\n // add defer to all scripts tags\n return str_replace( ' src', ' defer=\"defer\" src', $tag );\n}\nadd_filter( 'script_loader_tag', 'js_defer_attr', 10 );\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/5250412\">Here's more</a> about the <code>defer</code> attribute.</p>\n\n<h1>Alternative: place script to footer</h1>\n\n<p>It's also possible to replace all scripts to footer. Use the following CODE (instead of the above) to place all scripts in the footer:</p>\n\n<pre><code>function move_scripts_to_footer() {\n remove_action( 'wp_head', 'wp_print_scripts' );\n remove_action( 'wp_head', 'wp_print_head_scripts', 9 );\n remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );\n add_action( 'wp_footer', 'wp_print_scripts', 5 );\n add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );\n add_action( 'wp_footer', 'wp_print_head_scripts', 5 );\n}\nadd_action( 'wp_head', 'move_scripts_to_footer', -1 );\n</code></pre>\n"
},
{
"answer_id": 323026,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>You can eliminate render blocking JavaScript very easily by using different plugins, like <a href=\"https://wordpress.org/plugins/autoptimize/\" rel=\"nofollow noreferrer\">Autoptimize</a>. Follow these steps:</p>\n\n<ol>\n<li>Install and activate Autoptimize.</li>\n<li>Head to <strong>Settings > Autoptimize</strong>.</li>\n<li>Check the boxes beside \"<strong>Optimize JavaScript Code?</strong>\" and \"<strong>Optimize\nJavaScript Code?</strong>\" options.</li>\n<li>Click on <strong>Save Changes</strong> button.</li>\n</ol>\n\n<p>You can also use W3 Total Cache plugin to solve the issue. You will find the steps for applying it <a href=\"https://hostadvice.com/how-to/how-to-fix-render-blocking-javascript-and-css-of-your-wordpress-website/\" rel=\"nofollow noreferrer\">right here</a>.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113232/"
]
| I'm loading a list of products on an archive type page and creating a custom query to do so. I want to create a 'load more' functionality so that clicking the 'load more' button at the bottom of list loads the next 10 products.
I thought it would be as easy as using a variable to set 'posts\_per\_page' and simply increment it by 10 when the button is clicked. I get strange results however. This code is not the final code but just to illustrate this problem.
```
if(isset( $_POST['load-next-amount'] )){
$pageamount = 10
}
else {
$pageamount = 5;
}
```
So the first time this is loaded it resolves to false because the button hasny't yet been clicked, so posts\_per\_page will be set to 5. Then when clicking the button, you would expect 10 to load but for some reason it continues to load 5. If however I change the code to this:
```
if(isset( $_POST['load-next-amount'] )){
$pageamount = 4
}
else {
$pageamount = 5;
}
```
it will load 4. So I cannot increase the amount of posts\_per\_page through this variable, but I can decrease it. Strange.
Here is my query:
```
$myArgs = array(
'category' => '',
'category_name' => '',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'include' => '',
'exclude' => '',
'meta_key' => '_price_per_1hr_lesson',
'meta_value' => '',
'post_type' => 'job_listing',
'post_mime_type' => '',
'post_parent' => '',
'post__in' => $what,
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'job_listing_region' => "'" . $city . "'",
'post_status' => 'publish',
'posts_per_page' => $pageamount,
'suppress_filters' => true
);
$myquery = new WP_Query( $myArgs );
```
UPDATE: using print\_r I can see that the correct value is being assigned to the variable and that value is being correctly assigned to 'posts\_per\_page'. For whatever reason, it ignores it UNLESS it is LESS than the previously assigned value. For instance if I set the else statement to $pageamount = 20, the first time the page loads there will be 20, then if i click the button(sending the variable to the script which is 10) it will load 10. It will load any number of posts I hard code as long as it's less than 20.
Obviously there is something in WP that is setting a default or something. Still a bit of a newb to WP so I don't know. Looking at wp\_config and I dont' see anything. | You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your `functions.php` to load your scripts asynchronously.
This can get you started,
>
> Warning
>
>
>
loading JavaScript asynchronously will cause several issues with dependencies:
```
/*function to add async to all scripts*/
function js_async_attr($tag){
//Add async to all scripts tags
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
```
so you have to check your JS code and update it. |
257,253 | <p>I have problem in Wordpress after migrating my website.
In title tag (<code><title></code>) I have
<code>"&#8211;"</code>
instead of
<code>"-"</code></p>
<p>For the browser it's good, in the title it shows good.
But in html code is <code>"&#8211;"</code>....</p>
<p>Please help me <3</p>
| [
{
"answer_id": 257264,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 1,
"selected": false,
"text": "<h1>Background:</h1>\n<p>WordPress converts normal dash (-) to long dash (<code>–</code>), straight quotes to curly quotes and some other similar symbols and punctuations to their printer friendly versions using <code>wptexturize</code>.</p>\n<p>Generally it's recommended to leave them up to WordPress. However, occasionally, we may want to override this behaviour. For example, in case we are writing Programming CODE or command and want people to copy paste them.</p>\n<h1>Solution:</h1>\n<p>One way to avoid this conversion is to have these CODE inside <code><code></code></code> block. That way WordPress will know that they are meant to be kept as is. However, we may have already written it and don't want a rewrite. In that case, it's possible to stop WordPress to do these auto conversions all together by disabling <code>wptexturize</code>.</p>\n<p>For WordPress 4.0 and above, it's easy to do using the following CODE in a plugin or your theme's <code>functions.php</code> file:</p>\n<pre><code>add_filter( 'run_wptexturize', '__return_false' );\n</code></pre>\n<p>For before WordPress 4.0, you'll need a little more CODE:</p>\n<pre><code>foreach( array(\n 'bloginfo',\n 'the_content',\n 'the_excerpt',\n 'the_title',\n 'comment_text',\n 'comment_author',\n 'link_name',\n 'link_description',\n 'link_notes',\n 'list_cats',\n 'nav_menu_attr_title',\n 'nav_menu_description',\n 'single_post_title',\n 'single_cat_title',\n 'single_tag_title',\n 'single_month_title',\n 'term_description',\n 'term_name',\n 'widget_title',\n 'wp_title'\n) as $texturize_disable_for )\nremove_filter( $texturize_disable_for, 'wptexturize' );\n</code></pre>\n<p>Of course, you may choose to disable <code>wptexturize</code> only for part of your content. Say, to disable only for <code>title</code>, you may use:</p>\n<pre><code>remove_filter( 'the_title', 'wptexturize' );\n</code></pre>\n"
},
{
"answer_id": 257268,
"author": "Nicholas Koskowski",
"author_id": 92318,
"author_profile": "https://wordpress.stackexchange.com/users/92318",
"pm_score": -1,
"selected": false,
"text": "<p>Make sure that anything you are passing to the <code>wp_title();</code> function is wrapped in <code>esc_html();</code></p>\n\n<p>Example:</p>\n\n<p><code><title><?php esc_html(wp_title($YOURSTRINGHERE)); ?></title></code></p>\n\n<p>This will properly convert any HTML entities to their appropriate equivalents.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257253",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113800/"
]
| I have problem in Wordpress after migrating my website.
In title tag (`<title>`) I have
`"–"`
instead of
`"-"`
For the browser it's good, in the title it shows good.
But in html code is `"–"`....
Please help me <3 | Background:
===========
WordPress converts normal dash (-) to long dash (`–`), straight quotes to curly quotes and some other similar symbols and punctuations to their printer friendly versions using `wptexturize`.
Generally it's recommended to leave them up to WordPress. However, occasionally, we may want to override this behaviour. For example, in case we are writing Programming CODE or command and want people to copy paste them.
Solution:
=========
One way to avoid this conversion is to have these CODE inside `<code></code>` block. That way WordPress will know that they are meant to be kept as is. However, we may have already written it and don't want a rewrite. In that case, it's possible to stop WordPress to do these auto conversions all together by disabling `wptexturize`.
For WordPress 4.0 and above, it's easy to do using the following CODE in a plugin or your theme's `functions.php` file:
```
add_filter( 'run_wptexturize', '__return_false' );
```
For before WordPress 4.0, you'll need a little more CODE:
```
foreach( array(
'bloginfo',
'the_content',
'the_excerpt',
'the_title',
'comment_text',
'comment_author',
'link_name',
'link_description',
'link_notes',
'list_cats',
'nav_menu_attr_title',
'nav_menu_description',
'single_post_title',
'single_cat_title',
'single_tag_title',
'single_month_title',
'term_description',
'term_name',
'widget_title',
'wp_title'
) as $texturize_disable_for )
remove_filter( $texturize_disable_for, 'wptexturize' );
```
Of course, you may choose to disable `wptexturize` only for part of your content. Say, to disable only for `title`, you may use:
```
remove_filter( 'the_title', 'wptexturize' );
``` |
257,254 | <p>I want to include inline SVGs in a metabox textarea. </p>
<p>That's easy. What's killing me is how do I sanitize the textarea before saving the postmeta, and how do I escape it? </p>
<p>Halp? </p>
<p>Thanks!</p>
| [
{
"answer_id": 340313,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a PHP library that was created for sanitizing SVG files that may be worth looking into. <a href=\"https://github.com/darylldoyle/svg-sanitizer\" rel=\"nofollow noreferrer\">https://github.com/darylldoyle/svg-sanitizer</a></p>\n\n<p>Here is an example of how this could be used:</p>\n\n<pre><code>// Now do what you want with your clean SVG/XML data\n\nfunction your_save_meta( $post_id, $post, $update ) {\n\n // - Update the post's metadata.\n\n if ( isset( $_POST['svg_meta'] ) ) {\n\n // Load the sanitizer. (This path will need to be updated)\n use enshrined\\svgSanitize\\Sanitizer;\n\n // Create a new sanitizer instance\n $sanitizer = new Sanitizer();\n\n // Pass your meta data to the sanitizer and get it back clean\n $cleanSVG = $sanitizer->sanitize($_POST['svg_meta']);\n\n // Update your post meta\n update_post_meta( $post_id, 'svg_meta_name', $cleanSVG );\n\n }\n\n}\nadd_action( 'save_post', 'your_save_meta', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 379592,
"author": "Ian Dunn",
"author_id": 3898,
"author_profile": "https://wordpress.stackexchange.com/users/3898",
"pm_score": 0,
"selected": false,
"text": "<p>Safe SVG (<a href=\"https://wordpress.stackexchange.com/a/340313/3898\">mentioned by @Marc</a>) is by far the best WP plugin I've seen.</p>\n<p>It's important to note, though, that it's likely there are ways to bypass it. SVGs are insecure by design; we all think of them as images, but in reality they're mini XML applications.</p>\n<p><a href=\"https://github.com/cure53/DOMPurify\" rel=\"nofollow noreferrer\">DOMPurify</a> is the only reliably secure solution that I'm aware of. That's because it runs in JavaScript, so it can analyze objects after they've been parsed by the engine. It's impossible for PHP to do that. You can read more about it in <a href=\"https://core.trac.wordpress.org/ticket/24251\" rel=\"nofollow noreferrer\">#24251-core</a>.</p>\n<p>For most sites, though, Safe SVG is probably a good compromise. For a mission-critical/enterprise/ecommerce site, though, I'd recommend running it through DOMPurify (although it wont be easy).</p>\n<ol>\n<li>Hook into WP's upload process, probably via the <code>pre_move_uploaded_file</code> filter provided by <code>_wp_handle_upload()</code>.</li>\n<li>Get the value of the uploaded SVG from <code>$file</code> as a string, and make an HTTPS request to a Node.js API.</li>\n<li>Setup the Node app to accept the string, run it through DOMPurify, and return the result.</li>\n<li>The PHP plugin can then save the sanitized result.</li>\n</ol>\n<p>To be practical, though, it's probably better to just avoid SVGs in situations like this, and use an actual image format instead.</p>\n"
}
]
| 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257254",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93720/"
]
| I want to include inline SVGs in a metabox textarea.
That's easy. What's killing me is how do I sanitize the textarea before saving the postmeta, and how do I escape it?
Halp?
Thanks! | Here is a PHP library that was created for sanitizing SVG files that may be worth looking into. <https://github.com/darylldoyle/svg-sanitizer>
Here is an example of how this could be used:
```
// Now do what you want with your clean SVG/XML data
function your_save_meta( $post_id, $post, $update ) {
// - Update the post's metadata.
if ( isset( $_POST['svg_meta'] ) ) {
// Load the sanitizer. (This path will need to be updated)
use enshrined\svgSanitize\Sanitizer;
// Create a new sanitizer instance
$sanitizer = new Sanitizer();
// Pass your meta data to the sanitizer and get it back clean
$cleanSVG = $sanitizer->sanitize($_POST['svg_meta']);
// Update your post meta
update_post_meta( $post_id, 'svg_meta_name', $cleanSVG );
}
}
add_action( 'save_post', 'your_save_meta', 10, 3 );
``` |
257,281 | <p>I am working on a WordPress child theme where I do not have access to any markup other than the header.php. (I have access to child functions.php and the style.css)</p>
<p>The site has a body and a div#wrapper, but I would really like there to be 1 or 2 divs between those because I don't want to use body to create a column and currently, the only way to wrangle the whacky markup would be with the body. I would like to get a div that actually wraps the page contents in this case.</p>
<pre><code><html>
<body>
<section class='NEW-WRAPPING-ELEMENT'>
<div id='wrapper'>
...
</div>
<div id="footer'></div>
<div id="other'></div>
</section>
</body>
</html>
</code></pre>
<p>This markup probably worked just fine in most cases with a classic 960px absolutely positioned layout, but it's hard to work with when you want a malleable responsive layout.</p>
<p>I can use JavaScript and wrap them on page load, but it seems like it would be better to build it on the server - since I'm using PHP anyway. ALSO, you can see the flash of styling when the .master wrapper kicks in. No good!</p>
<p>I am removing <code>p</code> tags from images and wrapping things like inline images with a <code>figure</code> with <code>preg_wrap</code>. Can I / <em>should I</em> - use a similar technique to 'wrap' my everything in the body with another div? I do not know regex at all. I hacked this together but no go so far. Thoughts???</p>
<pre><code>function wrap_wrapper( $content ) {
// A regular expression of what to look for.
$pattern = '/<body>(.*?)<\/body>/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<section class="new-master">$1</section>';
return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'wrap_wrapper' );
</code></pre>
<p><a href="http://codepen.io/sheriffderek/pen/15b13233cfb96c7bff2b5f8f83b0c036/" rel="nofollow noreferrer">Here is a CodePen</a> with full markup example of what I have to work with:</p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.php.</p>\n</blockquote>\n\n<p>...but you do not state why this is. It seems to me that for a child theme to work well, you'd need at least a <code>functions.php</code> if not a template for content as well. If you can't access those or create those, I would say to your client, \"Here's your shitty website. This is the best I could do with the tools you gave me. I can do better if you grant access to more files.\"</p>\n\n<p>That's my first thought. My second thought is, your plan seems like it may work, if all the modifications you need are in the header. </p>\n\n<p>My last thought is more of a wondering: Can you create a plugin that would take over the work of the theme files you can't access?</p>\n"
},
{
"answer_id": 260397,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Can I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.</p>\n\n<p>The <code>the_content</code> filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.</p>\n\n<p>Unfortunately, there isn't a good way to filter the entire page.</p>\n\n<p>One way to accomplish this would be to use <code>ob_start()</code> and <code>ob_get_clean()</code> attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.</p>\n\n<p>Then we can do something with the content. Your regex was close, but not quite right.</p>\n\n<p>In your functions.php, add the following:</p>\n\n<pre><code>//* Hook into WordPress immediately before it starts output\nadd_action( 'wp_head', 'wpse_wp', -1 );\nfunction wpse_wp() {\n\n //* Start out buffering\n ob_start();\n\n //* Add action to get the buffer on shutdown\n add_action( 'shutdown', 'wpse_shutdown', -1 );\n}\n\nfunction wpse_shutdown() {\n\n //* Get the output buffer\n $content = ob_get_clean();\n\n //* Do something useful with the buffer\n\n //* Use preg_replace to add a <section> wrapper inside the <body> tag\n $pattern = \"/<body(.*?)>(.*?)<\\/body>/is\";\n $replacement = '<body$1><section class=\"new-master\">$2</section></body>';\n\n //* Print the content to the screen\n print( preg_replace( $pattern, $replacement, $content ) );\n}\n</code></pre>\n\n<blockquote>\n <p>Should I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option.</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27168/"
]
| I am working on a WordPress child theme where I do not have access to any markup other than the header.php. (I have access to child functions.php and the style.css)
The site has a body and a div#wrapper, but I would really like there to be 1 or 2 divs between those because I don't want to use body to create a column and currently, the only way to wrangle the whacky markup would be with the body. I would like to get a div that actually wraps the page contents in this case.
```
<html>
<body>
<section class='NEW-WRAPPING-ELEMENT'>
<div id='wrapper'>
...
</div>
<div id="footer'></div>
<div id="other'></div>
</section>
</body>
</html>
```
This markup probably worked just fine in most cases with a classic 960px absolutely positioned layout, but it's hard to work with when you want a malleable responsive layout.
I can use JavaScript and wrap them on page load, but it seems like it would be better to build it on the server - since I'm using PHP anyway. ALSO, you can see the flash of styling when the .master wrapper kicks in. No good!
I am removing `p` tags from images and wrapping things like inline images with a `figure` with `preg_wrap`. Can I / *should I* - use a similar technique to 'wrap' my everything in the body with another div? I do not know regex at all. I hacked this together but no go so far. Thoughts???
```
function wrap_wrapper( $content ) {
// A regular expression of what to look for.
$pattern = '/<body>(.*?)<\/body>/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<section class="new-master">$1</section>';
return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'wrap_wrapper' );
```
[Here is a CodePen](http://codepen.io/sheriffderek/pen/15b13233cfb96c7bff2b5f8f83b0c036/) with full markup example of what I have to work with: | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,284 | <p>I'm displaying three posts (custom post types) with a foreach loop, each displaying an audio player and some metadata. The audio is played via JW Player, which I am calling using their api. There is a function in the JW Player code that allows you to stop any other players from playing if you press one player.</p>
<p>Here's the whole loop. It does the job but I would like something more elegant and dynamic:</p>
<pre><code><?php
$posts = get_posts(array(
'numberposts' => 3,
'post_type' => 'audio'
));
if( $posts ):
$i = 1;
?>
<?php foreach( $posts as $post ) : ?>
<div class="media-container audio player-<?php echo $i; ?>">
<div id="player-<?php echo $i; ?>">Loading this Audio...</div>
<?php
if ($i == 1) :
$x1 = 2;
$x2 = 3;
elseif ($i == 2) :
$x1 = 1;
$x2 = 3;
elseif ($i == 3) :
$x1 = 1;
$x2 = 2;
endif;
?>
<script type="text/javaScript">
var playerInstance = jwplayer("player-<?php echo $i; ?>");
playerInstance.setup({
file: '<?php the_field("audio_upload"); ?>',
image: '<?php the_field("audio_image"); ?>',
events:{
onPlay: function() {
jwplayer('player-<?php echo $x1; ?>').stop();
jwplayer('player-<?php echo $x2; ?>').stop();
}
}
});
</script>
<div class="media-details">
<h2 class="audio-title"><?php the_field('name_of_audio'); ?> </h2>
</div>
</div>
<?php $i++; endforeach; wp_reset_postdata(); endif; ?>
</code></pre>
<p>I'm wondering if there isn't a way to dynamically get $x1 and $x2 rather than explicitly declaring the values like I am doing. For example if I decide to have 4 or 5 (or 10) posts show up on this page I would like to not have to change the code for $x1 and $x2. Any help would be appreciated.</p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.php.</p>\n</blockquote>\n\n<p>...but you do not state why this is. It seems to me that for a child theme to work well, you'd need at least a <code>functions.php</code> if not a template for content as well. If you can't access those or create those, I would say to your client, \"Here's your shitty website. This is the best I could do with the tools you gave me. I can do better if you grant access to more files.\"</p>\n\n<p>That's my first thought. My second thought is, your plan seems like it may work, if all the modifications you need are in the header. </p>\n\n<p>My last thought is more of a wondering: Can you create a plugin that would take over the work of the theme files you can't access?</p>\n"
},
{
"answer_id": 260397,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Can I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.</p>\n\n<p>The <code>the_content</code> filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.</p>\n\n<p>Unfortunately, there isn't a good way to filter the entire page.</p>\n\n<p>One way to accomplish this would be to use <code>ob_start()</code> and <code>ob_get_clean()</code> attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.</p>\n\n<p>Then we can do something with the content. Your regex was close, but not quite right.</p>\n\n<p>In your functions.php, add the following:</p>\n\n<pre><code>//* Hook into WordPress immediately before it starts output\nadd_action( 'wp_head', 'wpse_wp', -1 );\nfunction wpse_wp() {\n\n //* Start out buffering\n ob_start();\n\n //* Add action to get the buffer on shutdown\n add_action( 'shutdown', 'wpse_shutdown', -1 );\n}\n\nfunction wpse_shutdown() {\n\n //* Get the output buffer\n $content = ob_get_clean();\n\n //* Do something useful with the buffer\n\n //* Use preg_replace to add a <section> wrapper inside the <body> tag\n $pattern = \"/<body(.*?)>(.*?)<\\/body>/is\";\n $replacement = '<body$1><section class=\"new-master\">$2</section></body>';\n\n //* Print the content to the screen\n print( preg_replace( $pattern, $replacement, $content ) );\n}\n</code></pre>\n\n<blockquote>\n <p>Should I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option.</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109951/"
]
| I'm displaying three posts (custom post types) with a foreach loop, each displaying an audio player and some metadata. The audio is played via JW Player, which I am calling using their api. There is a function in the JW Player code that allows you to stop any other players from playing if you press one player.
Here's the whole loop. It does the job but I would like something more elegant and dynamic:
```
<?php
$posts = get_posts(array(
'numberposts' => 3,
'post_type' => 'audio'
));
if( $posts ):
$i = 1;
?>
<?php foreach( $posts as $post ) : ?>
<div class="media-container audio player-<?php echo $i; ?>">
<div id="player-<?php echo $i; ?>">Loading this Audio...</div>
<?php
if ($i == 1) :
$x1 = 2;
$x2 = 3;
elseif ($i == 2) :
$x1 = 1;
$x2 = 3;
elseif ($i == 3) :
$x1 = 1;
$x2 = 2;
endif;
?>
<script type="text/javaScript">
var playerInstance = jwplayer("player-<?php echo $i; ?>");
playerInstance.setup({
file: '<?php the_field("audio_upload"); ?>',
image: '<?php the_field("audio_image"); ?>',
events:{
onPlay: function() {
jwplayer('player-<?php echo $x1; ?>').stop();
jwplayer('player-<?php echo $x2; ?>').stop();
}
}
});
</script>
<div class="media-details">
<h2 class="audio-title"><?php the_field('name_of_audio'); ?> </h2>
</div>
</div>
<?php $i++; endforeach; wp_reset_postdata(); endif; ?>
```
I'm wondering if there isn't a way to dynamically get $x1 and $x2 rather than explicitly declaring the values like I am doing. For example if I decide to have 4 or 5 (or 10) posts show up on this page I would like to not have to change the code for $x1 and $x2. Any help would be appreciated. | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,286 | <p>I just need to get real password (before encrypt) when user is registering. I need to save that password in another table. How I access the real password before encrypt? </p>
<p>The reason for it is, I am doing a research about passwords. </p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.php.</p>\n</blockquote>\n\n<p>...but you do not state why this is. It seems to me that for a child theme to work well, you'd need at least a <code>functions.php</code> if not a template for content as well. If you can't access those or create those, I would say to your client, \"Here's your shitty website. This is the best I could do with the tools you gave me. I can do better if you grant access to more files.\"</p>\n\n<p>That's my first thought. My second thought is, your plan seems like it may work, if all the modifications you need are in the header. </p>\n\n<p>My last thought is more of a wondering: Can you create a plugin that would take over the work of the theme files you can't access?</p>\n"
},
{
"answer_id": 260397,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Can I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.</p>\n\n<p>The <code>the_content</code> filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.</p>\n\n<p>Unfortunately, there isn't a good way to filter the entire page.</p>\n\n<p>One way to accomplish this would be to use <code>ob_start()</code> and <code>ob_get_clean()</code> attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.</p>\n\n<p>Then we can do something with the content. Your regex was close, but not quite right.</p>\n\n<p>In your functions.php, add the following:</p>\n\n<pre><code>//* Hook into WordPress immediately before it starts output\nadd_action( 'wp_head', 'wpse_wp', -1 );\nfunction wpse_wp() {\n\n //* Start out buffering\n ob_start();\n\n //* Add action to get the buffer on shutdown\n add_action( 'shutdown', 'wpse_shutdown', -1 );\n}\n\nfunction wpse_shutdown() {\n\n //* Get the output buffer\n $content = ob_get_clean();\n\n //* Do something useful with the buffer\n\n //* Use preg_replace to add a <section> wrapper inside the <body> tag\n $pattern = \"/<body(.*?)>(.*?)<\\/body>/is\";\n $replacement = '<body$1><section class=\"new-master\">$2</section></body>';\n\n //* Print the content to the screen\n print( preg_replace( $pattern, $replacement, $content ) );\n}\n</code></pre>\n\n<blockquote>\n <p>Should I use a similar technique to 'wrap' my everything in the body with another div?</p>\n</blockquote>\n\n<p>It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option.</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113820/"
]
| I just need to get real password (before encrypt) when user is registering. I need to save that password in another table. How I access the real password before encrypt?
The reason for it is, I am doing a research about passwords. | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,301 | <p>I want to use jquery in my admin side programming but it seems there's no jquery loaded in the page at all and it load only at main website! Has my wordpress any problem which can't load jquery or I should do something extra to do it. However I put this code in function.php, but it not works:</p>
<pre><code>if(is_admin()){
function load_admin_script(){
wp_enqueue_script('jquery_script', "/wp-includes/js/jquery/jquery.js");
}
add_action('admin_enqueue_scripts','load_admin_script');
}
</code></pre>
| [
{
"answer_id": 257302,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to load Jquery, wordpress already provides a handler for it (its also the one in <code>/wp-includes/js/jquery/jquery.js</code>):</p>\n\n<pre><code> function load_admin_script(){\n wp_enqueue_script('jquery');\n }\n add_action('admin_enqueue_scripts','load_admin_script');\n</code></pre>\n\n<p>note that the jQuery in WordPress runs in noConflict mode.</p>\n"
},
{
"answer_id": 257303,
"author": "AddWeb Solution Pvt Ltd",
"author_id": 73643,
"author_profile": "https://wordpress.stackexchange.com/users/73643",
"pm_score": 0,
"selected": false,
"text": "<p>You can use add_action hook to load your jquery in your admin area like below code.</p>\n\n<pre><code><?php \nadd_action( 'admin_enqueue_scripts', 'load_jquery' );\nfunction load_jquery() {\n wp_enqueue_script('load_js',YOUR PATH.'/js/jquery.js');\n} \n?>\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112741/"
]
| I want to use jquery in my admin side programming but it seems there's no jquery loaded in the page at all and it load only at main website! Has my wordpress any problem which can't load jquery or I should do something extra to do it. However I put this code in function.php, but it not works:
```
if(is_admin()){
function load_admin_script(){
wp_enqueue_script('jquery_script', "/wp-includes/js/jquery/jquery.js");
}
add_action('admin_enqueue_scripts','load_admin_script');
}
``` | If you want to load Jquery, wordpress already provides a handler for it (its also the one in `/wp-includes/js/jquery/jquery.js`):
```
function load_admin_script(){
wp_enqueue_script('jquery');
}
add_action('admin_enqueue_scripts','load_admin_script');
```
note that the jQuery in WordPress runs in noConflict mode. |
257,317 | <p>I run WordPress version 4.7.2. and it uses jQuery version 1.12. I need to update this version to a higher one. I replaced it with a new version before, but when I upgrade WordPress core it is replaced with 1.12 again.
How can I change the version of jQuery that WordPress uses permanently?</p>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especially in the admin panel</strong>. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the <code>jQuery</code> version added in the core.</p>\n</blockquote>\n\n<p>If you are sure that you want to change the core <code>jQuery</code> version, in that case you may add the following CODE in your active theme's <code>functions.php</code> file (even better if you create a plugin for this):</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery' );\n // Change the URL if you want to load a local copy of jQuery from your own server.\n wp_register_script( 'jquery', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n}\nadd_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This will replace core <code>jQuery</code> version and instead load version <code>3.1.1</code> from Google's server.</p>\n\n<p>Also, although <strong><em>not recommended</em></strong>, you may use the following additional line of CODE to replace the jQuery version in <code>wp-admin</code> as well:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This way, even after updating WordPress, you'll have the version of <code>jQuery</code> as you want.</p>\n\n<h1>A slightly better function:</h1>\n\n<p>The <code>replace_core_jquery_version</code> function above also removes <code>jquery-migrate</code> script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of <code>jquery-migrate</code>. However, you can include a newer version of <code>jquery-migrate</code> as well. In that case, use the following function instead:</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery-core' );\n wp_register_script( 'jquery-core', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n wp_deregister_script( 'jquery-migrate' );\n wp_register_script( 'jquery-migrate', \"https://code.jquery.com/jquery-migrate-3.0.0.min.js\", array(), '3.0.0' );\n}\n</code></pre>\n"
},
{
"answer_id": 341920,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 4,
"selected": false,
"text": "<p>I have developed a plugin for this specific problem. The plugin doesn't mess with WordPress jQuery as it is only loaded in the front-end. See: <a href=\"https://wordpress.org/plugins/jquery-manager/\" rel=\"noreferrer\">jQuery Manager for WordPress</a></p>\n\n<blockquote>\n <h2>Why yet another jQuery Updater / Manager / Developer / Debugging tool?</h2>\n \n <p>Because none of the developer tools lets you select a specific\n version of jQuery and/or jQuery Migrate. Providing both the production\n and the minified version. See features below!</p>\n \n <p>✅ Only executed in the front-end, <strong>doesn't interfere with WordPress\n admin/backend and WP customizer</strong> (for compatibility reasons) See:\n <a href=\"https://core.trac.wordpress.org/ticket/45130\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/45130</a> and\n <a href=\"https://core.trac.wordpress.org/ticket/37110\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/37110</a></p>\n \n <p>✅ <strong>Turn on/off</strong> jQuery and/or jQuery Migrate</p>\n \n <p>✅ Activate a <strong>specific version</strong> of jQuery and/or jQuery Migrate</p>\n \n <p>And much more! The code is open source, so you could study\n it, learn from it and contribute.</p>\n</blockquote>\n\n<p><br></p>\n\n<h2>Almost everybody uses the incorrect handle</h2>\n\n<p>WordPress actually uses the jquery-core handle, not jquery:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\" rel=\"noreferrer\">https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226</a></p>\n\n<pre><code>// jQuery\n$scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.12.4' );\n$scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.12.4' );\n$scripts->add( 'jquery-migrate', \"/wp-includes/js/jquery/jquery-migrate$suffix.js\", array(), '1.4.1' );\n</code></pre>\n \n <p>The <strong>jquery</strong> handle is just an alias to load <strong>jquery-core</strong> with <strong>jquery-migrate</strong><br><br>See more info about aliases: <a href=\"https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\">wp_register_script multiple identifiers?</a></p>\n</blockquote>\n\n<h2>The correct way to do it</h2>\n\n<p>In my example below I use the official jQuery CDN at <a href=\"https://code.jquery.com\" rel=\"noreferrer\">https://code.jquery.com</a> I also use <strong>script_loader_tag</strong> so that I could add some CDN attributes.<br>\nYou could use the following code:</p>\n\n<pre><code>// Front-end not excuted in the wp admin and the wp customizer (for compatibility reasons)\n// See: https://core.trac.wordpress.org/ticket/45130 and https://core.trac.wordpress.org/ticket/37110\nfunction wp_jquery_manager_plugin_front_end_scripts() {\n $wp_admin = is_admin();\n $wp_customizer = is_customize_preview();\n\n // jQuery\n if ( $wp_admin || $wp_customizer ) {\n // echo 'We are in the WP Admin or in the WP Customizer';\n return;\n }\n else {\n // Deregister WP core jQuery, see https://github.com/Remzi1993/wp-jquery-manager/issues/2 and https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\n wp_deregister_script( 'jquery' ); // the jquery handle is just an alias to load jquery-core with jquery-migrate\n // Deregister WP jQuery\n wp_deregister_script( 'jquery-core' );\n // Deregister WP jQuery Migrate\n wp_deregister_script( 'jquery-migrate' );\n\n // Register jQuery in the head\n wp_register_script( 'jquery-core', 'https://code.jquery.com/jquery-3.3.1.min.js', array(), null, false );\n\n /**\n * Register jquery using jquery-core as a dependency, so other scripts could use the jquery handle\n * see https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\n * We first register the script and afther that we enqueue it, see why:\n * https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque\n * https://stackoverflow.com/questions/39653993/what-is-diffrence-between-wp-enqueue-script-and-wp-register-script\n */\n wp_register_script( 'jquery', false, array( 'jquery-core' ), null, false );\n wp_enqueue_script( 'jquery' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wp_jquery_manager_plugin_front_end_scripts' );\n\n\nfunction add_jquery_attributes( $tag, $handle ) {\n if ( 'jquery-core' === $handle ) {\n return str_replace( \"type='text/javascript'\", \"type='text/javascript' integrity='sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=' crossorigin='anonymous'\", $tag );\n }\n return $tag;\n}\nadd_filter( 'script_loader_tag', 'add_jquery_attributes', 10, 2 );\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112741/"
]
| I run WordPress version 4.7.2. and it uses jQuery version 1.12. I need to update this version to a higher one. I replaced it with a new version before, but when I upgrade WordPress core it is replaced with 1.12 again.
How can I change the version of jQuery that WordPress uses permanently? | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,324 | <p>I'm using the following code to determine if a checkbox has been ticked and then display some text if it has/hasn't as a test.</p>
<p>When its checked, it works fine and the text displays. </p>
<p>When its unchecked I get the message below on the two lines I have commented in my code below.</p>
<blockquote>
<p>Illegal string offset 'chec_checkbox_field_0'</p>
</blockquote>
<pre><code><?php
function webdev_init() {
?>
<h1>Title</h1>
<h2>WedDev Overlay Plugin Options</h2>
<form action='options.php' method='post'>
<h2>Checking</h2>
<?php
settings_fields( 'my_option' );
do_settings_sections( 'checking' );
submit_button();
?>
</form>
<?php
}
function chec_settings_init() {
register_setting( 'my_option', 'chec_settings' );
add_settings_section(
'chec_checking_section',
__( 'Your section description', 'wp' ),
'chec_settings_section_callback',
'checking'
);
add_settings_field(
'chec_checkbox_field_0',
__( 'Settings field description', 'wp' ),
'chec_checkbox_field_0_render',
'checking',
'chec_checking_section'
);
}
function chec_settings_section_callback() {
echo __( 'This section description', 'wp' );
}
function chec_checkbox_field_0_render() {
$options = get_option( 'chec_settings' );
?>
//Error message on line bellow
<input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />
<?php
}
$options = get_option( 'chec_settings' );
//Error message on line bellow
if ( $options['chec_checkbox_field_0'] == '1' ) {
echo 'Checked';
} else {
echo 'Unchecked';
}
</code></pre>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especially in the admin panel</strong>. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the <code>jQuery</code> version added in the core.</p>\n</blockquote>\n\n<p>If you are sure that you want to change the core <code>jQuery</code> version, in that case you may add the following CODE in your active theme's <code>functions.php</code> file (even better if you create a plugin for this):</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery' );\n // Change the URL if you want to load a local copy of jQuery from your own server.\n wp_register_script( 'jquery', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n}\nadd_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This will replace core <code>jQuery</code> version and instead load version <code>3.1.1</code> from Google's server.</p>\n\n<p>Also, although <strong><em>not recommended</em></strong>, you may use the following additional line of CODE to replace the jQuery version in <code>wp-admin</code> as well:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This way, even after updating WordPress, you'll have the version of <code>jQuery</code> as you want.</p>\n\n<h1>A slightly better function:</h1>\n\n<p>The <code>replace_core_jquery_version</code> function above also removes <code>jquery-migrate</code> script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of <code>jquery-migrate</code>. However, you can include a newer version of <code>jquery-migrate</code> as well. In that case, use the following function instead:</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery-core' );\n wp_register_script( 'jquery-core', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n wp_deregister_script( 'jquery-migrate' );\n wp_register_script( 'jquery-migrate', \"https://code.jquery.com/jquery-migrate-3.0.0.min.js\", array(), '3.0.0' );\n}\n</code></pre>\n"
},
{
"answer_id": 341920,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 4,
"selected": false,
"text": "<p>I have developed a plugin for this specific problem. The plugin doesn't mess with WordPress jQuery as it is only loaded in the front-end. See: <a href=\"https://wordpress.org/plugins/jquery-manager/\" rel=\"noreferrer\">jQuery Manager for WordPress</a></p>\n\n<blockquote>\n <h2>Why yet another jQuery Updater / Manager / Developer / Debugging tool?</h2>\n \n <p>Because none of the developer tools lets you select a specific\n version of jQuery and/or jQuery Migrate. Providing both the production\n and the minified version. See features below!</p>\n \n <p>✅ Only executed in the front-end, <strong>doesn't interfere with WordPress\n admin/backend and WP customizer</strong> (for compatibility reasons) See:\n <a href=\"https://core.trac.wordpress.org/ticket/45130\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/45130</a> and\n <a href=\"https://core.trac.wordpress.org/ticket/37110\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/37110</a></p>\n \n <p>✅ <strong>Turn on/off</strong> jQuery and/or jQuery Migrate</p>\n \n <p>✅ Activate a <strong>specific version</strong> of jQuery and/or jQuery Migrate</p>\n \n <p>And much more! The code is open source, so you could study\n it, learn from it and contribute.</p>\n</blockquote>\n\n<p><br></p>\n\n<h2>Almost everybody uses the incorrect handle</h2>\n\n<p>WordPress actually uses the jquery-core handle, not jquery:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\" rel=\"noreferrer\">https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226</a></p>\n\n<pre><code>// jQuery\n$scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.12.4' );\n$scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.12.4' );\n$scripts->add( 'jquery-migrate', \"/wp-includes/js/jquery/jquery-migrate$suffix.js\", array(), '1.4.1' );\n</code></pre>\n \n <p>The <strong>jquery</strong> handle is just an alias to load <strong>jquery-core</strong> with <strong>jquery-migrate</strong><br><br>See more info about aliases: <a href=\"https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\">wp_register_script multiple identifiers?</a></p>\n</blockquote>\n\n<h2>The correct way to do it</h2>\n\n<p>In my example below I use the official jQuery CDN at <a href=\"https://code.jquery.com\" rel=\"noreferrer\">https://code.jquery.com</a> I also use <strong>script_loader_tag</strong> so that I could add some CDN attributes.<br>\nYou could use the following code:</p>\n\n<pre><code>// Front-end not excuted in the wp admin and the wp customizer (for compatibility reasons)\n// See: https://core.trac.wordpress.org/ticket/45130 and https://core.trac.wordpress.org/ticket/37110\nfunction wp_jquery_manager_plugin_front_end_scripts() {\n $wp_admin = is_admin();\n $wp_customizer = is_customize_preview();\n\n // jQuery\n if ( $wp_admin || $wp_customizer ) {\n // echo 'We are in the WP Admin or in the WP Customizer';\n return;\n }\n else {\n // Deregister WP core jQuery, see https://github.com/Remzi1993/wp-jquery-manager/issues/2 and https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\n wp_deregister_script( 'jquery' ); // the jquery handle is just an alias to load jquery-core with jquery-migrate\n // Deregister WP jQuery\n wp_deregister_script( 'jquery-core' );\n // Deregister WP jQuery Migrate\n wp_deregister_script( 'jquery-migrate' );\n\n // Register jQuery in the head\n wp_register_script( 'jquery-core', 'https://code.jquery.com/jquery-3.3.1.min.js', array(), null, false );\n\n /**\n * Register jquery using jquery-core as a dependency, so other scripts could use the jquery handle\n * see https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\n * We first register the script and afther that we enqueue it, see why:\n * https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque\n * https://stackoverflow.com/questions/39653993/what-is-diffrence-between-wp-enqueue-script-and-wp-register-script\n */\n wp_register_script( 'jquery', false, array( 'jquery-core' ), null, false );\n wp_enqueue_script( 'jquery' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wp_jquery_manager_plugin_front_end_scripts' );\n\n\nfunction add_jquery_attributes( $tag, $handle ) {\n if ( 'jquery-core' === $handle ) {\n return str_replace( \"type='text/javascript'\", \"type='text/javascript' integrity='sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=' crossorigin='anonymous'\", $tag );\n }\n return $tag;\n}\nadd_filter( 'script_loader_tag', 'add_jquery_attributes', 10, 2 );\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113840/"
]
| I'm using the following code to determine if a checkbox has been ticked and then display some text if it has/hasn't as a test.
When its checked, it works fine and the text displays.
When its unchecked I get the message below on the two lines I have commented in my code below.
>
> Illegal string offset 'chec\_checkbox\_field\_0'
>
>
>
```
<?php
function webdev_init() {
?>
<h1>Title</h1>
<h2>WedDev Overlay Plugin Options</h2>
<form action='options.php' method='post'>
<h2>Checking</h2>
<?php
settings_fields( 'my_option' );
do_settings_sections( 'checking' );
submit_button();
?>
</form>
<?php
}
function chec_settings_init() {
register_setting( 'my_option', 'chec_settings' );
add_settings_section(
'chec_checking_section',
__( 'Your section description', 'wp' ),
'chec_settings_section_callback',
'checking'
);
add_settings_field(
'chec_checkbox_field_0',
__( 'Settings field description', 'wp' ),
'chec_checkbox_field_0_render',
'checking',
'chec_checking_section'
);
}
function chec_settings_section_callback() {
echo __( 'This section description', 'wp' );
}
function chec_checkbox_field_0_render() {
$options = get_option( 'chec_settings' );
?>
//Error message on line bellow
<input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />
<?php
}
$options = get_option( 'chec_settings' );
//Error message on line bellow
if ( $options['chec_checkbox_field_0'] == '1' ) {
echo 'Checked';
} else {
echo 'Unchecked';
}
``` | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,325 | <p>Since plugin updates might bring some unexpected issues to the compatibilies. </p>
<p>Is it recommended to modify plugin version value
to fool the wordpress plugin update system if priority is to turn off plugin out-of-date warnings from wordpress backend ?</p>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especially in the admin panel</strong>. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the <code>jQuery</code> version added in the core.</p>\n</blockquote>\n\n<p>If you are sure that you want to change the core <code>jQuery</code> version, in that case you may add the following CODE in your active theme's <code>functions.php</code> file (even better if you create a plugin for this):</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery' );\n // Change the URL if you want to load a local copy of jQuery from your own server.\n wp_register_script( 'jquery', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n}\nadd_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This will replace core <code>jQuery</code> version and instead load version <code>3.1.1</code> from Google's server.</p>\n\n<p>Also, although <strong><em>not recommended</em></strong>, you may use the following additional line of CODE to replace the jQuery version in <code>wp-admin</code> as well:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );\n</code></pre>\n\n<p>This way, even after updating WordPress, you'll have the version of <code>jQuery</code> as you want.</p>\n\n<h1>A slightly better function:</h1>\n\n<p>The <code>replace_core_jquery_version</code> function above also removes <code>jquery-migrate</code> script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of <code>jquery-migrate</code>. However, you can include a newer version of <code>jquery-migrate</code> as well. In that case, use the following function instead:</p>\n\n<pre><code>function replace_core_jquery_version() {\n wp_deregister_script( 'jquery-core' );\n wp_register_script( 'jquery-core', \"https://code.jquery.com/jquery-3.1.1.min.js\", array(), '3.1.1' );\n wp_deregister_script( 'jquery-migrate' );\n wp_register_script( 'jquery-migrate', \"https://code.jquery.com/jquery-migrate-3.0.0.min.js\", array(), '3.0.0' );\n}\n</code></pre>\n"
},
{
"answer_id": 341920,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 4,
"selected": false,
"text": "<p>I have developed a plugin for this specific problem. The plugin doesn't mess with WordPress jQuery as it is only loaded in the front-end. See: <a href=\"https://wordpress.org/plugins/jquery-manager/\" rel=\"noreferrer\">jQuery Manager for WordPress</a></p>\n\n<blockquote>\n <h2>Why yet another jQuery Updater / Manager / Developer / Debugging tool?</h2>\n \n <p>Because none of the developer tools lets you select a specific\n version of jQuery and/or jQuery Migrate. Providing both the production\n and the minified version. See features below!</p>\n \n <p>✅ Only executed in the front-end, <strong>doesn't interfere with WordPress\n admin/backend and WP customizer</strong> (for compatibility reasons) See:\n <a href=\"https://core.trac.wordpress.org/ticket/45130\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/45130</a> and\n <a href=\"https://core.trac.wordpress.org/ticket/37110\" rel=\"noreferrer\">https://core.trac.wordpress.org/ticket/37110</a></p>\n \n <p>✅ <strong>Turn on/off</strong> jQuery and/or jQuery Migrate</p>\n \n <p>✅ Activate a <strong>specific version</strong> of jQuery and/or jQuery Migrate</p>\n \n <p>And much more! The code is open source, so you could study\n it, learn from it and contribute.</p>\n</blockquote>\n\n<p><br></p>\n\n<h2>Almost everybody uses the incorrect handle</h2>\n\n<p>WordPress actually uses the jquery-core handle, not jquery:</p>\n\n<blockquote>\n <p><a href=\"https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\" rel=\"noreferrer\">https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226</a></p>\n\n<pre><code>// jQuery\n$scripts->add( 'jquery', false, array( 'jquery-core', 'jquery-migrate' ), '1.12.4' );\n$scripts->add( 'jquery-core', '/wp-includes/js/jquery/jquery.js', array(), '1.12.4' );\n$scripts->add( 'jquery-migrate', \"/wp-includes/js/jquery/jquery-migrate$suffix.js\", array(), '1.4.1' );\n</code></pre>\n \n <p>The <strong>jquery</strong> handle is just an alias to load <strong>jquery-core</strong> with <strong>jquery-migrate</strong><br><br>See more info about aliases: <a href=\"https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\">wp_register_script multiple identifiers?</a></p>\n</blockquote>\n\n<h2>The correct way to do it</h2>\n\n<p>In my example below I use the official jQuery CDN at <a href=\"https://code.jquery.com\" rel=\"noreferrer\">https://code.jquery.com</a> I also use <strong>script_loader_tag</strong> so that I could add some CDN attributes.<br>\nYou could use the following code:</p>\n\n<pre><code>// Front-end not excuted in the wp admin and the wp customizer (for compatibility reasons)\n// See: https://core.trac.wordpress.org/ticket/45130 and https://core.trac.wordpress.org/ticket/37110\nfunction wp_jquery_manager_plugin_front_end_scripts() {\n $wp_admin = is_admin();\n $wp_customizer = is_customize_preview();\n\n // jQuery\n if ( $wp_admin || $wp_customizer ) {\n // echo 'We are in the WP Admin or in the WP Customizer';\n return;\n }\n else {\n // Deregister WP core jQuery, see https://github.com/Remzi1993/wp-jquery-manager/issues/2 and https://github.com/WordPress/WordPress/blob/91da29d9afaa664eb84e1261ebb916b18a362aa9/wp-includes/script-loader.php#L226\n wp_deregister_script( 'jquery' ); // the jquery handle is just an alias to load jquery-core with jquery-migrate\n // Deregister WP jQuery\n wp_deregister_script( 'jquery-core' );\n // Deregister WP jQuery Migrate\n wp_deregister_script( 'jquery-migrate' );\n\n // Register jQuery in the head\n wp_register_script( 'jquery-core', 'https://code.jquery.com/jquery-3.3.1.min.js', array(), null, false );\n\n /**\n * Register jquery using jquery-core as a dependency, so other scripts could use the jquery handle\n * see https://wordpress.stackexchange.com/questions/283828/wp-register-script-multiple-identifiers\n * We first register the script and afther that we enqueue it, see why:\n * https://wordpress.stackexchange.com/questions/82490/when-should-i-use-wp-register-script-with-wp-enqueue-script-vs-just-wp-enque\n * https://stackoverflow.com/questions/39653993/what-is-diffrence-between-wp-enqueue-script-and-wp-register-script\n */\n wp_register_script( 'jquery', false, array( 'jquery-core' ), null, false );\n wp_enqueue_script( 'jquery' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wp_jquery_manager_plugin_front_end_scripts' );\n\n\nfunction add_jquery_attributes( $tag, $handle ) {\n if ( 'jquery-core' === $handle ) {\n return str_replace( \"type='text/javascript'\", \"type='text/javascript' integrity='sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=' crossorigin='anonymous'\", $tag );\n }\n return $tag;\n}\nadd_filter( 'script_loader_tag', 'add_jquery_attributes', 10, 2 );\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257325",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63121/"
]
| Since plugin updates might bring some unexpected issues to the compatibilies.
Is it recommended to modify plugin version value
to fool the wordpress plugin update system if priority is to turn off plugin out-of-date warnings from wordpress backend ? | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,337 | <p>My local WordPress installation on XAMPP seems to have a wrong time setting. When I do</p>
<pre><code>date( 'Y-m-d H:i:s' );
</code></pre>
<p>I get <strong>2017-02-21 10:46:43</strong> as result. However my PCs time really is <strong>2017-02-21 11:46:43</strong>, so my WordPress is one hour behind.</p>
<p>Now I already did, what was recommended <a href="https://stackoverflow.com/questions/15359451/xampp-php-date-function-time-is-different-from-local-machine-time">here</a> and changed <strong>date.timezone</strong> in the <strong>php.ini</strong> to my timezone and restarted the apache afterwards, since I thought the problem might be cause by XAMPP. But still I get the wrong time displayed.</p>
<p>I also went to <strong>settings -> general</strong> in WordPress and changed the timezone there to the correct one. The local time shown there is correct: </p>
<p><em>"Local time is 2017-02-21 11:46:43"</em></p>
<p>But when I use the function, it's still wrong. Do you have any idea, what else could cause this problem?</p>
| [
{
"answer_id": 257338,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 3,
"selected": false,
"text": "<p><code>date()</code> is a <code>PHP</code> function depending on your server settings. You can go around that by using the WordPress function:</p>\n\n<pre><code>current_time( 'Y-m-d H:i:s' );\n</code></pre>\n\n<p>This function takes the settings in <code>wp-admin</code> into account.</p>\n"
},
{
"answer_id": 257343,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 0,
"selected": false,
"text": "<p>use wordpress functions to get time according to WordPress settings and time zone such as <code>the_time</code> and <code>the_date</code></p>\n\n<pre><code> the_date('F j, Y');\n the_time('g:i a');\n</code></pre>\n"
},
{
"answer_id": 346014,
"author": "ender.center",
"author_id": 174182,
"author_profile": "https://wordpress.stackexchange.com/users/174182",
"pm_score": 0,
"selected": false,
"text": "<p>It seems Wordpress overrides the php Timezone to save all dates as UTC.\nBut they also do a poor job in converting it back to local time.</p>\n\n<p>I have run into the same problem and did some testing to find a solution.</p>\n\n<p>1st of all this is not a PHP timezone Problem, to confirm this I put a test.php into my theme folder and opened it directly (/wp-content/themes/theme/test.php)</p>\n\n<p>if I use the date() function in this file the time is correct.</p>\n\n<p>but if I put this lines into e.g. my themes home.php</p>\n\n<pre><code>print date('Y-m-d H:i:s');\nprint current_time('Y-m-d H:i:s');\n</code></pre>\n\n<p>I get the wrong time when I visit the Homepage.</p>\n\n<p>date() returns UTC and current_time() return the time of the right timezone but it does not include DST so I'm still 1 hour off.</p>\n\n<p>what i ended up doing is this:</p>\n\n<pre><code>$row = $wpdb->get_row( \"SELECT CURRENT_TIMESTAMP() AS timestamp\", ARRAY_A);\n$timestamp = $row['timestamp'];\n</code></pre>\n\n<p>if your database has the right config for your timezone you can ask your database for the Timestamp.</p>\n\n<p>But this also has some downsides, it will only work if your Database has right timezone and it always does a Query to the database so you should not use it to excessive.</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105498/"
]
| My local WordPress installation on XAMPP seems to have a wrong time setting. When I do
```
date( 'Y-m-d H:i:s' );
```
I get **2017-02-21 10:46:43** as result. However my PCs time really is **2017-02-21 11:46:43**, so my WordPress is one hour behind.
Now I already did, what was recommended [here](https://stackoverflow.com/questions/15359451/xampp-php-date-function-time-is-different-from-local-machine-time) and changed **date.timezone** in the **php.ini** to my timezone and restarted the apache afterwards, since I thought the problem might be cause by XAMPP. But still I get the wrong time displayed.
I also went to **settings -> general** in WordPress and changed the timezone there to the correct one. The local time shown there is correct:
*"Local time is 2017-02-21 11:46:43"*
But when I use the function, it's still wrong. Do you have any idea, what else could cause this problem? | `date()` is a `PHP` function depending on your server settings. You can go around that by using the WordPress function:
```
current_time( 'Y-m-d H:i:s' );
```
This function takes the settings in `wp-admin` into account. |
257,355 | <p>How to use live images on a local WP install? I want to do something like the code down here in the <code>wp-config.php</code>. Problem is that the <code>siteurl</code> must be a relative path and cant be a url. I want to set up a local environment to test some parts offline and need to show the images.</p>
<pre><code>if ($_SERVER['SERVER_ADMIN'] == 'dev') {
define('WP_HOME','http://localhost/siteurl.com/public_html/');
define('WP_SITEURL','http://localhost/siteurl.com/public_html/');
// use live images
define( 'UPLOADS', 'http://siteurl.com/wp-content/uploads/' );
}
</code></pre>
| [
{
"answer_id": 257359,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": true,
"text": "<p>Try to filter the output URLs temporarily to replace them with online images, using the following code:</p>\n\n<pre><code>add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {\n\n // For thumbnails\n if ( $size ) {\n switch ( $size ) {\n case 'thumbnail':\n case 'medium':\n case 'medium-large':\n case 'large':\n $image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );\n break;\n default:\n break;\n }\n } else {\n $image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );\n }\n return $image;\n}, 10, 3 );\n</code></pre>\n\n<p>This will replace any string containing <code>localhost</code> with your online domain's name. However, you can't modify or do anything with the image's, it's just for correcting the URL for development purposes.</p>\n\n<p>Note that you should use the domain name without <code>http://</code> or any <code>/</code> before the domain's name.</p>\n\n<p>Delete this function from your theme's <code>functions.php</code> after you are done with it.</p>\n"
},
{
"answer_id": 257393,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 3,
"selected": false,
"text": "<p>The best way to do it is to use URL Rewrites.</p>\n\n<p>This way you'll not have to do any change before uploading CODE to your server back again. Try the following CODE in your <code>.htaccess</code> file:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\n\n# custom rules for loading server images or any other uploaded media files\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{HTTP_HOST} ^localhost$\nRewriteRule ^.*/uploads/(.*)$ http://siteurl.com/wp-content/uploads/$1 [L,R=301,NC]\n\n# default WordPress rules\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n</code></pre>\n\n<p>Adjust your live domain to <code>siteurl.com</code> accordingly in the above code and your server images will be loaded when you develop from localhost.</p>\n\n<p>Also, with this line: <code>RewriteCond %{REQUEST_FILENAME} !-f</code>, the web server will check first if the image is available in your <code>localhost</code> (with the exact same name), and load from server only if it's not available locally. If you want to load server image even if that same image exists locally, then simply remove that line.</p>\n"
},
{
"answer_id": 358316,
"author": "Giorgio25b",
"author_id": 62097,
"author_profile": "https://wordpress.stackexchange.com/users/62097",
"pm_score": 1,
"selected": false,
"text": "<p>I tweaked @scott answer to fit my needs with this variation:</p>\n\n<pre><code># custom rules for loading server images or any other uploaded media files\nRewriteCond %{REQUEST_URI} ^/wp-content/uploads/[^\\/]*/.*$\nRewriteRule ^(.*)$ https://siteurl.com/$1 [QSA,L]\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54693/"
]
| How to use live images on a local WP install? I want to do something like the code down here in the `wp-config.php`. Problem is that the `siteurl` must be a relative path and cant be a url. I want to set up a local environment to test some parts offline and need to show the images.
```
if ($_SERVER['SERVER_ADMIN'] == 'dev') {
define('WP_HOME','http://localhost/siteurl.com/public_html/');
define('WP_SITEURL','http://localhost/siteurl.com/public_html/');
// use live images
define( 'UPLOADS', 'http://siteurl.com/wp-content/uploads/' );
}
``` | Try to filter the output URLs temporarily to replace them with online images, using the following code:
```
add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {
// For thumbnails
if ( $size ) {
switch ( $size ) {
case 'thumbnail':
case 'medium':
case 'medium-large':
case 'large':
$image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );
break;
default:
break;
}
} else {
$image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );
}
return $image;
}, 10, 3 );
```
This will replace any string containing `localhost` with your online domain's name. However, you can't modify or do anything with the image's, it's just for correcting the URL for development purposes.
Note that you should use the domain name without `http://` or any `/` before the domain's name.
Delete this function from your theme's `functions.php` after you are done with it. |
257,366 | <p>How do I create a complete organisation's database, where I can access tables and perform custom SQL requests.
I can use PHP and mySQL, I am actually working on a WordPress theme.
And I am trying to do something like this:</p>
<pre><code>+----------+ +------------+ +------------+
| Book | | Borrow | | Reader |
|----------| |------------| |------------|
|codeBook# |_____|codeBook# | |codeReader# |
|title | |codeReader# |_____|name |
|datepub | |date | |age |
+----------+ +------------+ |contacts |
+------------+
</code></pre>
<p>Some explanation and link will be great</p>
| [
{
"answer_id": 257368,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>You can do that accessing the <a href=\"https://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpmyadmin</a> dashboard of your host, but that is no the right way to do it, i recommend you to research and learn about:</p>\n\n<ul>\n<li><a href=\"https://codex.wordpress.org/Post_Types\" rel=\"nofollow noreferrer\">Custom Post Types</a></li>\n<li><a href=\"https://codex.wordpress.org/Taxonomies\" rel=\"nofollow noreferrer\">Custom Taxonomies</a></li>\n</ul>\n"
},
{
"answer_id": 257378,
"author": "Ninda",
"author_id": 109858,
"author_profile": "https://wordpress.stackexchange.com/users/109858",
"pm_score": 0,
"selected": false,
"text": "<p>I found a solution:</p>\n\n<ul>\n<li>I have already created <code>custom post type</code> for different needs(eg. Book and Reader).</li>\n<li>I will manually create the remaining tables(eg. Borrow) in phpMyAdmin </li>\n<li>Then use comment <code>$wpdb->get_results( 'SELECT....');</code> for custom query</li>\n</ul>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257366",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109858/"
]
| How do I create a complete organisation's database, where I can access tables and perform custom SQL requests.
I can use PHP and mySQL, I am actually working on a WordPress theme.
And I am trying to do something like this:
```
+----------+ +------------+ +------------+
| Book | | Borrow | | Reader |
|----------| |------------| |------------|
|codeBook# |_____|codeBook# | |codeReader# |
|title | |codeReader# |_____|name |
|datepub | |date | |age |
+----------+ +------------+ |contacts |
+------------+
```
Some explanation and link will be great | You can do that accessing the [phpmyadmin](https://www.phpmyadmin.net/) dashboard of your host, but that is no the right way to do it, i recommend you to research and learn about:
* [Custom Post Types](https://codex.wordpress.org/Post_Types)
* [Custom Taxonomies](https://codex.wordpress.org/Taxonomies) |
257,370 | <p>Here's my code:</p>
<pre><code>add_action('admin_menu', 'test_plugin_setup_menu'); /**/
function test_plugin_setup_menu(){ /**/
add_submenu_page('options-general.php','Forhandler options side','Forhandler Options', 'manage_options', 'mine-første-options', 'test_init'); /**/
} /**/
function test_init(){ /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init(){
register_setting( 'mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate' );
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_text_string', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='plugin_checkbox' name='mine_plugin_options[plugin_checkbox]' type='checkbox' value='true' />";
}
// validate our options
function mine_plugin_options_validate($input) {
/*
$options = get_option('mine_plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options; */
}
</code></pre>
<p>It says that the settings have been saved, but the checkbox reverts back to not being clicked.</p>
<p>I'm pretty new to the whole "create your own options" thing, so any help would be appreciated. I followed this tutorial to make the code: <a href="http://ottopress.com/2009/wordpress-settings-api-tutorial/" rel="nofollow noreferrer">http://ottopress.com/2009/wordpress-settings-api-tutorial/</a></p>
| [
{
"answer_id": 257371,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you're missing the <code>checked=\"checked\"</code> value from your input...</p>\n\n<p>Try something like this:</p>\n\n<pre><code>$options = get_option('mine_plugin_options');\n$checked = ($options == 'true' ? ' checked=\"checked\"' : '');\necho \"<input id='plugin_checkbox' name='mine_plugin_options[plugin_checkbox]' type='checkbox' value='true' {$checked} />\";\n</code></pre>\n"
},
{
"answer_id": 257376,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>Don't comment out your validation code remember you are using it to validate the data, so its returning nothing right now, so its saving nothing, try this:</p>\n\n<pre><code>add_action('admin_bar_menu', 'make_parent_node', 999);\n\nfunction make_parent_node($wp_admin_bar) {\n $args = array(\n 'id' => 'test1234', // id of the existing child node (New > Post)\n 'title' => 'test', // alter the title of existing node\n 'parent' => 'new-content', // set parent to false to make it a top level (parent) node\n 'href' => admin_url('admin.php?page=enter_timesheet')\n );\n $wp_admin_bar->add_node($args);\n}\n\nadd_action('admin_menu', 'test_plugin_setup_menu');\n\nfunction test_plugin_setup_menu() { /**/\n add_submenu_page('options-general.php', 'Forhandler options side', 'Forhandler Options', 'manage_options', 'mine-første-options', 'test_init');\n}\n\n/**/\n\nfunction test_init() { /**/\n //echo \"<h1>Hello World!</h1>\";\n ?>\n <div>\n <h1>Codehero Dealers</h1>\n <form action=\"options.php\" method=\"post\">\n <?php settings_fields('mine_plugin_options'); ?>\n <?php do_settings_sections('mine-første-options'); ?>\n\n <input name=\"Submit\" type=\"submit\" value=\"<?php esc_attr_e('Save Changes'); ?>\" />\n </form>\n </div>\n <?php\n}\n\nfunction mine_plugin_section_text() {\n echo '<p>Her finder du indstillinger til forhandler delen.</p>';\n}\n\n// add the admin settings and such\nadd_action('admin_init', 'mine_plugin_admin_init');\n\nfunction mine_plugin_admin_init() {\n register_setting('mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate');\n\n add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');\n\n add_settings_field('mine_plugin_checkbox', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');\n\n}\n\nfunction mine_plugin_setting_string() {\n\n $options = get_option('mine_plugin_options');\n\n echo \"<input id='mine_plugin_checkbox' name='mine_plugin_options[checkbox]' type='checkbox' value='1'\" . checked( 1, $options['checkbox'], false ) . \" />\";\n}\n\n// validate our options\nfunction mine_plugin_options_validate($input) {\n\n $newinput['checkbox'] = trim($input['checkbox']);\n return $newinput;\n}\n</code></pre>\n\n<p>Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can use the WordPress <code>checked</code> function.</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113286/"
]
| Here's my code:
```
add_action('admin_menu', 'test_plugin_setup_menu'); /**/
function test_plugin_setup_menu(){ /**/
add_submenu_page('options-general.php','Forhandler options side','Forhandler Options', 'manage_options', 'mine-første-options', 'test_init'); /**/
} /**/
function test_init(){ /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init(){
register_setting( 'mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate' );
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_text_string', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='plugin_checkbox' name='mine_plugin_options[plugin_checkbox]' type='checkbox' value='true' />";
}
// validate our options
function mine_plugin_options_validate($input) {
/*
$options = get_option('mine_plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options; */
}
```
It says that the settings have been saved, but the checkbox reverts back to not being clicked.
I'm pretty new to the whole "create your own options" thing, so any help would be appreciated. I followed this tutorial to make the code: <http://ottopress.com/2009/wordpress-settings-api-tutorial/> | Don't comment out your validation code remember you are using it to validate the data, so its returning nothing right now, so its saving nothing, try this:
```
add_action('admin_bar_menu', 'make_parent_node', 999);
function make_parent_node($wp_admin_bar) {
$args = array(
'id' => 'test1234', // id of the existing child node (New > Post)
'title' => 'test', // alter the title of existing node
'parent' => 'new-content', // set parent to false to make it a top level (parent) node
'href' => admin_url('admin.php?page=enter_timesheet')
);
$wp_admin_bar->add_node($args);
}
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu() { /**/
add_submenu_page('options-general.php', 'Forhandler options side', 'Forhandler Options', 'manage_options', 'mine-første-options', 'test_init');
}
/**/
function test_init() { /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init() {
register_setting('mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate');
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_checkbox', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='mine_plugin_checkbox' name='mine_plugin_options[checkbox]' type='checkbox' value='1'" . checked( 1, $options['checkbox'], false ) . " />";
}
// validate our options
function mine_plugin_options_validate($input) {
$newinput['checkbox'] = trim($input['checkbox']);
return $newinput;
}
```
Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can use the WordPress `checked` function. |
257,384 | <p>I have created a custom page that I have called mypage.php.</p>
<p>It is in my template folder with al the other pages (index.php, page.php, ...)</p>
<p>I want this page to be opened when i click on the below code.</p>
<pre><code><a href="<?php site_url(); ?>/mypage.php">Go to page</a>
</code></pre>
<p>When I click on the link the url in my browser look like: <a href="http://localhost:8888/mypage.php" rel="nofollow noreferrer">http://localhost:8888/mypage.php</a> which I guess is correct.</p>
<p>BUT it uses index.php as template ignoring the code I have into mypage.php </p>
<p>So all i am getting at the moment is an empty page with only my header and footer.</p>
<p>Is it possible to use pages in this way with Wordpress? I had a look online and on this site but I haven't been able to find a solution for this problem.</p>
| [
{
"answer_id": 257385,
"author": "shishir mishra",
"author_id": 111219,
"author_profile": "https://wordpress.stackexchange.com/users/111219",
"pm_score": 1,
"selected": false,
"text": "<p>@Martina Sartor, you can use wordpress custom template process. Add a the below comment to the file you wish to make your custom page. Then go to the admin area and create a page, and select your custom template for that page. </p>\n\n<p>Please review</p>\n\n<pre><code><?php \n/*\nTemplate Name: Full-width layout\nTemplate Post Type: post, page, event\n*/\n// Page code here...\n</code></pre>\n\n<p>mention your template name here </p>\n\n<p>You can also review wordpress documentation for same.</p>\n\n<p><a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a></p>\n"
},
{
"answer_id": 257386,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<p>WordPress doesn't load templates that way.</p>\n\n<h1>First: give the template a name:</h1>\n\n<p>To load a page template, first you'll have to make sure your template has a name. To do that, you'll have to have the following CODE in your template file (here <code>mypage.php</code>):</p>\n\n<pre><code><?php\n/**\n * Template Name: My Page\n */\n</code></pre>\n\n<p>Once you have the above PHP comment, WordPress will recognise it as a template file.</p>\n\n<h1>Then, assign the template to a page:</h1>\n\n<p>Now you'll have to create a WordPress <code>page</code> (from <code>wp-admin</code>).</p>\n\n<p>While you create the <code>page</code>, WordPress will give you the option to choose a custom template (if there is one). After you choose the template and <code>Publish</code>, that page will use your <code>mypage.php</code> file as a template.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hikDh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hikDh.png\" alt=\"Add Page Template\"></a></p>\n"
},
{
"answer_id": 257392,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 0,
"selected": false,
"text": "<p>what you are looking to do is inserting custom php files inside your theme but sadly WP will not let you use .php files easily but fortunately it provides an alternate and more efficient way for including .php files.</p>\n\n<p>WordPress provides <code>get_template_part</code> function & <code>custom page templates</code>. you can use these methods instead.</p>\n\n<p>above answer has explained page templates and in addition to that you can use your custom php files included into that template or anywhere else using <code>get_template_part</code> function. this works same as <code>require</code> or <code>include</code> native php functions. </p>\n\n<p><strong>template</strong></p>\n\n<pre><code><?php\n/**\n * Template Name: My Page template\n */\n</code></pre>\n\n<p>php file to be included for example is <code>some-file.php</code> inside root folder. then you would write </p>\n\n<pre><code>get_template_part( 'some', 'file' );\n</code></pre>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111936/"
]
| I have created a custom page that I have called mypage.php.
It is in my template folder with al the other pages (index.php, page.php, ...)
I want this page to be opened when i click on the below code.
```
<a href="<?php site_url(); ?>/mypage.php">Go to page</a>
```
When I click on the link the url in my browser look like: <http://localhost:8888/mypage.php> which I guess is correct.
BUT it uses index.php as template ignoring the code I have into mypage.php
So all i am getting at the moment is an empty page with only my header and footer.
Is it possible to use pages in this way with Wordpress? I had a look online and on this site but I haven't been able to find a solution for this problem. | WordPress doesn't load templates that way.
First: give the template a name:
================================
To load a page template, first you'll have to make sure your template has a name. To do that, you'll have to have the following CODE in your template file (here `mypage.php`):
```
<?php
/**
* Template Name: My Page
*/
```
Once you have the above PHP comment, WordPress will recognise it as a template file.
Then, assign the template to a page:
====================================
Now you'll have to create a WordPress `page` (from `wp-admin`).
While you create the `page`, WordPress will give you the option to choose a custom template (if there is one). After you choose the template and `Publish`, that page will use your `mypage.php` file as a template.
[](https://i.stack.imgur.com/hikDh.png) |
257,403 | <p>I have a partial that I call around the website at various points. This partial simply displays the latest Post.</p>
<p>It looks like so:</p>
<pre><code><?php
$args = array(
'posts_per_page' => 1,
'order' => 'desc'
);
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
if (has_post_thumbnail( $post->ID ) ){
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );
}
?>
<a href="<?php echo get_the_permalink(); ?>"><h3><?php echo get_the_title(); ?></h3></a>
<?php if(!empty($featured_image)): ?>
<a href="<?php echo get_the_permalink(); ?>">
<img src="<?php echo $featured_image[0]; ?>" alt="" width="250" class="pull-left">
</a>
<?php endif; ?>
<p>
<?php echo get_the_excerpt(); ?>
</p>
<a href="<?php echo get_the_permalink(); ?>" class="btn btn-brand-dark">more</a>
<div class="clearfix"></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</code></pre>
<p>This works fine until I 'Sticky' a post. Then I get 2 posts instead of 1.</p>
<p>How can I amend all queries so that <code>posts_per_page</code> has the requested number of posts, regardless of sticky posts?</p>
<p>So in the example above, I'm currently getting <strong>2</strong> posts (despite requesting 1), but I want the latest post, whether that's a sticky post or not.</p>
<p>I know about <code>ignore_sticky_posts</code> parameter, but that will ignore the sticky post, which I don't want to do. If there's a sticky post it should be first.</p>
| [
{
"answer_id": 257404,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p><strike>If you want your query to ignore if a post is sticky and dont have it at the top of your ordered query:</strike></p>\n\n<pre><code>//$args = array(\n// 'posts_per_page' => 1,\n// 'order' => 'desc'\n// 'ignore_sticky_posts' => 1 //set this\n//);\n</code></pre>\n\n<p><strike>with this the sticky posts will not be ignored, what will be ignored is their status of <code>sticky</code>, the sticky posts will still be in your result, what <code>'ignore_sticky_posts'</code> does is tell the query to not bring the posts that are sticky to the top if you are ordering them.</strike></p>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>If you want just 1, remove the While loop logic:</p>\n\n<pre><code><?php\n$args = array(\n 'posts_per_page' => 1,\n 'order' => 'desc'\n);\nquery_posts($args);\n\nif ( have_posts() ) :\n\n if (has_post_thumbnail( $post->ID ) ){\n $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );\n }\n ?>\n <a href=\"<?php echo get_the_permalink(); ?>\"><h3><?php echo get_the_title(); ?></h3></a>\n <?php if(!empty($featured_image)): ?>\n <a href=\"<?php echo get_the_permalink(); ?>\">\n <img src=\"<?php echo $featured_image[0]; ?>\" alt=\"\" width=\"250\" class=\"pull-left\">\n </a>\n <?php endif; ?>\n <p>\n <?php echo get_the_excerpt(); ?>\n </p>\n <a href=\"<?php echo get_the_permalink(); ?>\" class=\"btn btn-brand-dark\">more</a>\n <div class=\"clearfix\"></div>\n<?php\n\nendif;\n\nwp_reset_postdata();\n?>\n</code></pre>\n\n<p>you can even remove the <code>'posts_per_page' => 1</code> the output will be the first one.</p>\n"
},
{
"answer_id": 257412,
"author": "Ted",
"author_id": 44012,
"author_profile": "https://wordpress.stackexchange.com/users/44012",
"pm_score": 0,
"selected": false,
"text": "<p>Try using if(! is_sticky()) </p>\n\n<pre><code><?php\n$args = array(\n 'posts_per_page' => 1,\n 'order' => 'desc'\n);\nquery_posts($args);\n\nif ( have_posts() ) :\n while ( have_posts() ) : the_post();\n if(! is_sticky()) {\n if (has_post_thumbnail( $post->ID ) ){\n $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );\n }\n ?>\n <a href=\"<?php echo get_the_permalink(); ?>\"><h3><?php echo get_the_title(); ?></h3></a>\n <?php if(!empty($featured_image)): ?>\n <a href=\"<?php echo get_the_permalink(); ?>\">\n <img src=\"<?php echo $featured_image[0]; ?>\" alt=\"\" width=\"250\" class=\"pull-left\">\n </a>\n <?php endif; ?>\n <p>\n <?php echo get_the_excerpt(); ?>\n </p>\n <a href=\"<?php echo get_the_permalink(); ?>\" class=\"btn btn-brand-dark\">more</a>\n <div class=\"clearfix\"></div>\n<?php } \n endwhile;\nendif;\n\nwp_reset_postdata();\n?>\n</code></pre>\n\n<p>Please note, this will completely prevent any sticky posts from appearing. </p>\n"
},
{
"answer_id": 257434,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 0,
"selected": false,
"text": "<p>I just noticed your comment that you wanted to accomplish this via a filter, so\nhere you go (this basically expounds on the comments I've made on your original question and <a href=\"https://wordpress.stackexchange.com/questions/257403/how-can-i-allow-sticky-posts-but-cap-the-query-to-1-post/#257404\">@DavidLee's answer</a>).</p>\n\n<p>The following will result in 1 and only 1 post, regardless of stickies.\nIf the most recently published post <strong>is</strong> sticky, you will get it. If the most recently\npublished post <strong>is not</strong> sticky, you will <em>still</em> get it. And, you will get no other\nposts, sticky or otherwise.</p>\n\n<pre><code>add_filter ('pre_get_posts', 'get_only_one_post') ;\n\nfunction\nget_only_one_post ($wp_query)\n{\n if (is_admin () || !$wp_query->is_main_query ()) {\n // we're not in the Main Loop, so return the query unmodified\n return ($wp_query) ;\n }\n\n // order by most recently published 1st\n // this isn't really necesary (since it is the default),\n // but include it just in case some other filter has modified that default\n $wp_query->set ('orderby', 'date') ;\n $wp_query->set ('order', 'DESC') ;\n\n // limit to 1 post, not counting stickies\n $wp_query->set ('posts_per_page', 1) ;\n\n // disable the special processing of sticky posts.\n // without this, ALL sticky posts will be returned, whether they match\n // the rest of the query_vars or not\n $wp_query->set ('ignore_sticky_posts', true) ;\n\n return ($wp_query) ;\n}\n</code></pre>\n\n<h1>Explanation</h1>\n\n<h2>Without <code>'ignore_sticky_posts' => true</code></h2>\n\n<p>The following is done:</p>\n\n<blockquote>\n <ol>\n <li>retrieve posts according to query vars, including respecting <code>posts_per_page</code> and <code>orderby</code>\n \n <ul>\n <li>any sticky posts that match query vars will already be included in the results</li>\n </ul></li>\n <li>move sticky posts that are included in the results to the front of the list</li>\n <li>retreive <strong>all</strong> sticky posts\n \n <ol>\n <li>those not already in the results are preprend to the list\n \n <ul>\n <li>it is this step that potentially causes the results to contain more than <code>posts_per_page</code> posts being returned</li>\n <li>See <a href=\"https://core.trac.wordpress.org/browser/tags/4.7.2/src/wp-includes/class-wp-query.php#L2966\" rel=\"nofollow noreferrer\">Lines 2966-2979, of the source for WP_Query</a></li>\n </ul></li>\n </ol></li>\n </ol>\n</blockquote>\n\n<h2>With <code>'ignore_sticky_posts' => true</code></h2>\n\n<p>The following is done:</p>\n\n<blockquote>\n <ol>\n <li>retrieve posts according to query vars, including respecting <code>posts_per_page</code> and <code>orderby</code>\n \n <ul>\n <li>any sticky posts that match query vars will already be included in the results</li>\n </ul></li>\n </ol>\n</blockquote>\n\n<h1>Edit: Additional answer</h1>\n\n<p>OK, try this:</p>\n\n<pre><code>add_filter ('pre_get_posts', 'set_posts_per_page_on_front_end_main_query') ;\nadd_filter ('the_posts', 'respect_posts_per_page') ;\n\nfunction\nrespect_posts_per_page ($posts, $wp_query)\n{\n return (array_slice ($posts, 0, $wp_query->get ('posts_per_page', count ($posts)))) ;\n}\n\nfunction\nset_posts_per_page_on_front_end_main_query ($wp_query)\n{\n if ( is_admin () || !$wp_query->is_main_query ()) {\n return ($wp_query) ;\n }\n\n $wp_query->set ('posts_per_page', 1) ;\n\n return ($wp_query) ;\n}\n</code></pre>\n"
},
{
"answer_id": 257523,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a way to force the exact <code>posts_per_page</code> value in <code>WP_Query</code>, regardless of sticky posts or custom post injects:</p>\n\n<pre><code>$args = [\n 'posts_per_page' => 1,\n '_exact_posts_per_page' => true // <-- our custom input argument\n];\n</code></pre>\n\n<p>by using our custom <code>_exact_posts_per_page</code> input argument.</p>\n\n<p>I'm sure this has been implemented many times before, but I didn't find it at the moment, so let us try to implement it with this demo plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Exact Posts Per Pages \n * Description: Activated through the '_exact_posts_per_page' bool argument of WP_Query \n * Plugin URI: http://wordpress.stackexchange.com/a/257523/26350 \n */\n\nadd_filter( 'the_posts', function( $posts, \\WP_Query $q )\n{\n if( \n wp_validate_boolean( $q->get( '_exact_posts_per_page' ) )\n && ! empty( $posts ) \n && is_int( $q->get( 'posts_per_page' ) ) \n )\n $posts = array_slice( $posts, 0, absint( $q->get( 'posts_per_page' ) ) );\n\n return $posts;\n\n}, 999, 2 ); // <-- some late priority here!\n</code></pre>\n\n<p>Here we use the <code>the_posts</code> filter to slice the array, no matter if it contains sticky posts or not.</p>\n\n<p>The <code>the_posts</code> filter is not applied if the <code>suppress_filters</code> input argument of <code>WP_Query</code> is <code>true</code>.</p>\n\n<p><strong>Note</strong> that <code>query_posts()</code> is not recommended in plugins or themes. Check out the many warnings in the <em>Code reference</em> <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Hope you can test it further and adjust to your needs!</p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56935/"
]
| I have a partial that I call around the website at various points. This partial simply displays the latest Post.
It looks like so:
```
<?php
$args = array(
'posts_per_page' => 1,
'order' => 'desc'
);
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
if (has_post_thumbnail( $post->ID ) ){
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );
}
?>
<a href="<?php echo get_the_permalink(); ?>"><h3><?php echo get_the_title(); ?></h3></a>
<?php if(!empty($featured_image)): ?>
<a href="<?php echo get_the_permalink(); ?>">
<img src="<?php echo $featured_image[0]; ?>" alt="" width="250" class="pull-left">
</a>
<?php endif; ?>
<p>
<?php echo get_the_excerpt(); ?>
</p>
<a href="<?php echo get_the_permalink(); ?>" class="btn btn-brand-dark">more</a>
<div class="clearfix"></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
```
This works fine until I 'Sticky' a post. Then I get 2 posts instead of 1.
How can I amend all queries so that `posts_per_page` has the requested number of posts, regardless of sticky posts?
So in the example above, I'm currently getting **2** posts (despite requesting 1), but I want the latest post, whether that's a sticky post or not.
I know about `ignore_sticky_posts` parameter, but that will ignore the sticky post, which I don't want to do. If there's a sticky post it should be first. | Here's a way to force the exact `posts_per_page` value in `WP_Query`, regardless of sticky posts or custom post injects:
```
$args = [
'posts_per_page' => 1,
'_exact_posts_per_page' => true // <-- our custom input argument
];
```
by using our custom `_exact_posts_per_page` input argument.
I'm sure this has been implemented many times before, but I didn't find it at the moment, so let us try to implement it with this demo plugin:
```
<?php
/**
* Plugin Name: Exact Posts Per Pages
* Description: Activated through the '_exact_posts_per_page' bool argument of WP_Query
* Plugin URI: http://wordpress.stackexchange.com/a/257523/26350
*/
add_filter( 'the_posts', function( $posts, \WP_Query $q )
{
if(
wp_validate_boolean( $q->get( '_exact_posts_per_page' ) )
&& ! empty( $posts )
&& is_int( $q->get( 'posts_per_page' ) )
)
$posts = array_slice( $posts, 0, absint( $q->get( 'posts_per_page' ) ) );
return $posts;
}, 999, 2 ); // <-- some late priority here!
```
Here we use the `the_posts` filter to slice the array, no matter if it contains sticky posts or not.
The `the_posts` filter is not applied if the `suppress_filters` input argument of `WP_Query` is `true`.
**Note** that `query_posts()` is not recommended in plugins or themes. Check out the many warnings in the *Code reference* [here](https://developer.wordpress.org/reference/functions/query_posts/).
Hope you can test it further and adjust to your needs! |
257,405 | <p>I am new to WordPress Plugins development, and I just started working with the widget. My question is: What are the limitations of WordPress Widget?</p>
<p>I tried to use jQuery to make the Widget Form more interactive/dynamic, but it doesn't seem to work at all. For example, I have a button that when clicked will add a string of "Hello!" to a div that has id "here".</p>
<pre><code><div id="here"></div>
<input type="button" id="add" value="Click Me!" " />
<script>
jQuery(document).ready(function(){
//call when the button is click
$(document).on('click', '#add', function() {
$('#here').append('<p>Hello</p>');
});
});
</script>
</code></pre>
<ol>
<li><p>Why doesn't the paragraph of "Hello" show up on the form? Is it because widget form prevent it from doing so?</p></li>
<li><p>I also heard about Backbone.js that refreshes the front-end, but I am not sure if that will work. </p></li>
<li><p>If possible, please explain how the whole wordpress widget class work. Thank you in advance!</p></li>
</ol>
<p><strong>Update: I already tried what are suggested, but it still doesn't work. Here are my code.</strong></p>
<p><strong>repeat.php</strong> </p>
<pre><code> <?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input',
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
?>
<div id="here"></div>
<input type="button" id="addRepeat" value="Click Me!" />
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
function repeat_field_widget_scripts() {
wp_enqueue_script( 'repeat-field-widget-scripts', get_template_directory_uri() . '/repeat.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'repeat_field_widget_scripts' );
</code></pre>
<p><strong>repeat.js</strong></p>
<pre><code> jQuery(document).ready(function($){
//call when the button is click
$("#addRepeat").click(function() {
$('#here').append('<p>Hello</p>');
});
});
</code></pre>
| [
{
"answer_id": 257415,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Widget forms are tricky for JS manipulation. In general you should never use IDs to detect elements in the form, but a combination of classes and <code>find()</code>, <code>parent()</code> etc.</p>\n\n<p>The reason is that there might be more than one form on the HTML page. For sure on the widget admin page there is a \"template\" form that is not displayed and IIRC is used to generate the form for a new widget. This means that there will be at least two element with the same ID, and an attempt to access them by DOM APIs will not give a consistent result.</p>\n"
},
{
"answer_id": 258297,
"author": "Sengngy Kouch",
"author_id": 113869,
"author_profile": "https://wordpress.stackexchange.com/users/113869",
"pm_score": 3,
"selected": true,
"text": "<p>Thank you <strong>Dave Romsey</strong> and <strong>Mark Kaplun</strong> for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.</p>\n\n<p><strong>Solution:</strong> </p>\n\n<p>We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called \"spotlight_image_link1, spotlight_image_link2, etc\". Then in the \"form function\" give their id using php code. Please read my code below for more information.</p>\n\n<p><strong>What can my solution do?</strong> </p>\n\n<p>Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read. </p>\n\n<p><strong>Here what it looks like:</strong> \n<a href=\"https://i.stack.imgur.com/Z6oZD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z6oZD.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Logic behind the scene:</strong> </p>\n\n<ul>\n<li>whenever the \"Click me!\" button is clicked, a spotlight will be added.</li>\n<li>There is a tracker array called \"tracker\" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the \"Click me!\" button.</li>\n<li>When the \"delete spotlight\" is clicked, remove that specific spotlight, and re-enable the \"Click me!\" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.</li>\n<li>The spotlight is saved only if and only if the input is not empty. That condition is in the \"while\" loop of the \"form\" function.</li>\n</ul>\n\n<p><strong>Limitation:</strong></p>\n\n<p>As of now, whenever, we clicked \"Save\", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet. </p>\n\n<p><strong>Source code:</strong> </p>\n\n<ul>\n<li>As of WordPress 4.7.2, it works without any error.</li>\n<li>Put all the source code into \"repeat.php\" file in your plugin directory. If you don't know how, please google it.</li>\n</ul>\n\n<p><strong>repeat.php</strong></p>\n\n<pre><code> <?php\n/**\n * Plugin Name: Repeat Field\n *\n */\n\n class repeat_field_widget extends WP_Widget {\n\n /**\n * Sets up the widgets name etc\n */\n public function __construct() {\n $widget_ops = array(\n 'classname' => 'repeat_field_widget',\n 'description' => 'Repeat Field for Name input'\n );\n parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );\n $tracker1;\n }\n\n /**\n * Outputs the content of the widget\n *\n * @param array $args\n * @param array $instance\n */\n public function widget( $args, $instance ) {\n // outputs the content of the widget\n $spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';\n $spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';\n\n /**============== Spotlight 1 =========================*/\n $spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';\n $spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';\n $spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';\n $spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';\n $spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';\n $spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';\n\n /**============== Spotlight 2 =========================*/\n $spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';\n $spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';\n $spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';\n $spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';\n $spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';\n $spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';\n }\n\n /**\n * Outputs the options form on admin\n *\n * @param array $instance The widget options\n */\n public function form( $instance ) {\n // outputs the options form on admin\n $instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',\n 'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));\n\n //Create Add and delete button\n $spotlight_add_row = $instance['spotlight_add_row'];\n $spotlight_row_appender = $instance['spotlight_row_appender'];\n\n /**================== Spotlight 1 ==============*/\n $spotlight_image_link1 = $instance['spotlight_image_link1'];\n $spotlight_add_image1 = $instance['spotlight_add_image1'];\n $spotlight_image_preview1 = $instance['spotlight_image_preview1'];\n $spotlight_name1 = $instance['spotlight_name1'];\n $spotlight_description1 = $instance['spotlight_description1'];\n $spotlight_link1 = $instance['spotlight_link1'];\n\n /**================== Spotlight 2 ==============*/\n $spotlight_image_link2 = $instance['spotlight_image_link2'];\n $spotlight_add_image2 = $instance['spotlight_add_image2'];\n $spotlight_image_preview2 = $instance['spotlight_image_preview2'];\n $spotlight_name2 = $instance['spotlight_name2'];\n $spotlight_description2 = $instance['spotlight_description2'];\n $spotlight_link2 = $instance['spotlight_link2'];\n\n $starter = 1; //Store which number to continue adding spotlight.\n $num = 1;\n $max_spotlight = 2; //number of spotlight allowed.\n static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.\n\n while($num <= $max_spotlight){\n $tempImage = 'spotlight_image_link' . $num;\n\n if ($$tempImage != ''){\n $starter++;\n $tracker[$num - 1] = 1;\n?>\n <!-- Image input -->\n <div>\n <p class=\"spotlight-para\">Spotlight <?php echo $num; ?></p>\n <p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->\n <label for=\"<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>\"><?php esc_attr_e( 'Image\\'s link:', 'text_domain' ); ?></label>\n <input\n class=\"widefat\"\n id=\"<?php echo $this->get_field_id($tempImage); ?>\"\n name=\"<?php echo $this->get_field_name($tempImage); ?>\"\n type=\"text\"\n value=\"<?php echo esc_attr($$tempImage); ?>\"\n />\n <input style=\"float:right;\" id=\"delete-spotlight\" name=\"<?php echo $tempDeleteName; ?>\" type=\"button\" value=\"Delete Spotlight\" class=\"button\"/>\n <br />\n </p>\n </div>\n<?php\n }\n $num++;\n }\n $id_prefix = $this->get_field_id(''); //get the widget prefix id.\n?>\n <span id=\"<?php echo $this->get_field_id('spotlight_row_appender'); ?>\"> </span>\n <div>\n <br />\n <input\n class=\"button\"\n type=\"button\"\n id=\"<?php echo $this->get_field_id('spotlight_add_row'); ?>\"\n value=\"Click Me!\"\n onclick=\"repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;\"\n />\n </div>\n\n <script>\n jQuery(document).ready(function($){\n var tracker = <?php echo json_encode($tracker); ?>;\n var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.\n\n //disbale add button when reaches max spotlight.\n if(tracker.every(x => x > 0)){\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr(\"disabled\",true);\n }\n\n repeater = {\n //TRY to mass Number into this function........\n uploader :function(widget_id, widget_id_string){\n //Find the non active element\n var i;\n for (i = 0; i < <?php echo $max_spotlight; ?>; i++){\n if ( tracker[i] == 0){\n c1 = i;\n break;\n }\n }\n c1++;\n //alert(c1);\n\n\n\n $(\"#\" + widget_id_string + \"spotlight_row_appender\").append('<div> <p class=\"spotlight-para\">Spotlight '+c1+'</p><p> <label for=\"<?php echo esc_attr( $this->get_field_id( \"spotlight_image_link'+c1+'\")); ?>\"><?php esc_attr_e( 'Image\\'s link:', 'text_domain' ); ?></label> <input class=\"widefat\" id=\"<?php echo $this->get_field_id(\"spotlight_image_link'+c1+'\"); ?>\" name=\"<?php echo $this->get_field_name(\"spotlight_image_link'+c1+'\"); ?>\" type=\"text\" value=\"\" /> <input style=\"float:right;\"id=\"delete-spotlight\" name=\"deletespotlight_'+c1+'\" type=\"button\" value=\"Delete Spotlight\" class=\"button\"/><br /> </p></div>');\n //check element as active\n tracker[c1-1] = 1;\n\n //if all element is > 0, disable the deleteButton.\n if(tracker.every(x => x > 0)){\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr(\"disabled\",true);\n }\n //alert(c1);\n return false;\n }\n };\n\n $(document).on('click', '#delete-spotlight', function() {\n\n $(this).parent().parent().remove(); //remove the field.\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr(\"disabled\"); //reset add button.\n\n //Get the name, and parse to get the ID.\n var deleteButtonName = this.name;\n var stringDeleteButton = deleteButtonName.split(\"_\").pop();\n var deleteButtonID = parseInt(stringDeleteButton);\n\n tracker[deleteButtonID-1] = 0; //reset element\n //alert(tracker);\n });\n\n });\n </script>\n <?php\n }\n\n /**\n * Processing widget options on save\n *\n * @param array $new_instance The new options\n * @param array $old_instance The previous options\n */\n public function update( $new_instance, $old_instance ) {\n // processes widget options to be saved\n $instance = $old_instance;\n $instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);\n $instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);\n\n $increment = 1;\n while ( $increment <= 2 ){\n //increment variables\n $increment_image_link = 'spotlight_image_link' . $increment;\n $increment_add_image = 'spotlight_add_image' . $increment;\n $increment_image_preview = 'spotlight_image_preview' . $increment;\n $increment_description = 'spotlight_description' . $increment;\n $increment_name = 'spotlight_name' . $increment;\n $increment_link = 'spotlight_link' . $increment;\n\n $instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );\n $instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );\n $instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);\n $instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );\n $instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );\n $instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );\n\n $increment++;\n }\n $starter = 1;\n $num = 1;\n\n return $instance;\n }\n}\n\n\nfunction register_repeat_field_widget() {\n register_widget( 'repeat_field_widget' );\n}\nadd_action( 'widgets_init', 'register_repeat_field_widget' );\n</code></pre>\n\n<p><strong>Quick Note:</strong></p>\n\n<p>I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. </p>\n"
}
]
| 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113869/"
]
| I am new to WordPress Plugins development, and I just started working with the widget. My question is: What are the limitations of WordPress Widget?
I tried to use jQuery to make the Widget Form more interactive/dynamic, but it doesn't seem to work at all. For example, I have a button that when clicked will add a string of "Hello!" to a div that has id "here".
```
<div id="here"></div>
<input type="button" id="add" value="Click Me!" " />
<script>
jQuery(document).ready(function(){
//call when the button is click
$(document).on('click', '#add', function() {
$('#here').append('<p>Hello</p>');
});
});
</script>
```
1. Why doesn't the paragraph of "Hello" show up on the form? Is it because widget form prevent it from doing so?
2. I also heard about Backbone.js that refreshes the front-end, but I am not sure if that will work.
3. If possible, please explain how the whole wordpress widget class work. Thank you in advance!
**Update: I already tried what are suggested, but it still doesn't work. Here are my code.**
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input',
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
?>
<div id="here"></div>
<input type="button" id="addRepeat" value="Click Me!" />
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
function repeat_field_widget_scripts() {
wp_enqueue_script( 'repeat-field-widget-scripts', get_template_directory_uri() . '/repeat.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'repeat_field_widget_scripts' );
```
**repeat.js**
```
jQuery(document).ready(function($){
//call when the button is click
$("#addRepeat").click(function() {
$('#here').append('<p>Hello</p>');
});
});
``` | Thank you **Dave Romsey** and **Mark Kaplun** for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.
**Solution:**
We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called "spotlight\_image\_link1, spotlight\_image\_link2, etc". Then in the "form function" give their id using php code. Please read my code below for more information.
**What can my solution do?**
Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read.
**Here what it looks like:**
[](https://i.stack.imgur.com/Z6oZD.png)
**Logic behind the scene:**
* whenever the "Click me!" button is clicked, a spotlight will be added.
* There is a tracker array called "tracker" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the "Click me!" button.
* When the "delete spotlight" is clicked, remove that specific spotlight, and re-enable the "Click me!" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.
* The spotlight is saved only if and only if the input is not empty. That condition is in the "while" loop of the "form" function.
**Limitation:**
As of now, whenever, we clicked "Save", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet.
**Source code:**
* As of WordPress 4.7.2, it works without any error.
* Put all the source code into "repeat.php" file in your plugin directory. If you don't know how, please google it.
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input'
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
$tracker1;
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
$spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';
$spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';
/**============== Spotlight 1 =========================*/
$spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';
$spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';
$spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';
$spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';
$spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';
$spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';
/**============== Spotlight 2 =========================*/
$spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';
$spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';
$spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';
$spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';
$spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';
$spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
$instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',
'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));
//Create Add and delete button
$spotlight_add_row = $instance['spotlight_add_row'];
$spotlight_row_appender = $instance['spotlight_row_appender'];
/**================== Spotlight 1 ==============*/
$spotlight_image_link1 = $instance['spotlight_image_link1'];
$spotlight_add_image1 = $instance['spotlight_add_image1'];
$spotlight_image_preview1 = $instance['spotlight_image_preview1'];
$spotlight_name1 = $instance['spotlight_name1'];
$spotlight_description1 = $instance['spotlight_description1'];
$spotlight_link1 = $instance['spotlight_link1'];
/**================== Spotlight 2 ==============*/
$spotlight_image_link2 = $instance['spotlight_image_link2'];
$spotlight_add_image2 = $instance['spotlight_add_image2'];
$spotlight_image_preview2 = $instance['spotlight_image_preview2'];
$spotlight_name2 = $instance['spotlight_name2'];
$spotlight_description2 = $instance['spotlight_description2'];
$spotlight_link2 = $instance['spotlight_link2'];
$starter = 1; //Store which number to continue adding spotlight.
$num = 1;
$max_spotlight = 2; //number of spotlight allowed.
static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.
while($num <= $max_spotlight){
$tempImage = 'spotlight_image_link' . $num;
if ($$tempImage != ''){
$starter++;
$tracker[$num - 1] = 1;
?>
<!-- Image input -->
<div>
<p class="spotlight-para">Spotlight <?php echo $num; ?></p>
<p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->
<label for="<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label>
<input
class="widefat"
id="<?php echo $this->get_field_id($tempImage); ?>"
name="<?php echo $this->get_field_name($tempImage); ?>"
type="text"
value="<?php echo esc_attr($$tempImage); ?>"
/>
<input style="float:right;" id="delete-spotlight" name="<?php echo $tempDeleteName; ?>" type="button" value="Delete Spotlight" class="button"/>
<br />
</p>
</div>
<?php
}
$num++;
}
$id_prefix = $this->get_field_id(''); //get the widget prefix id.
?>
<span id="<?php echo $this->get_field_id('spotlight_row_appender'); ?>"> </span>
<div>
<br />
<input
class="button"
type="button"
id="<?php echo $this->get_field_id('spotlight_add_row'); ?>"
value="Click Me!"
onclick="repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
/>
</div>
<script>
jQuery(document).ready(function($){
var tracker = <?php echo json_encode($tracker); ?>;
var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.
//disbale add button when reaches max spotlight.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
repeater = {
//TRY to mass Number into this function........
uploader :function(widget_id, widget_id_string){
//Find the non active element
var i;
for (i = 0; i < <?php echo $max_spotlight; ?>; i++){
if ( tracker[i] == 0){
c1 = i;
break;
}
}
c1++;
//alert(c1);
$("#" + widget_id_string + "spotlight_row_appender").append('<div> <p class="spotlight-para">Spotlight '+c1+'</p><p> <label for="<?php echo esc_attr( $this->get_field_id( "spotlight_image_link'+c1+'")); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id("spotlight_image_link'+c1+'"); ?>" name="<?php echo $this->get_field_name("spotlight_image_link'+c1+'"); ?>" type="text" value="" /> <input style="float:right;"id="delete-spotlight" name="deletespotlight_'+c1+'" type="button" value="Delete Spotlight" class="button"/><br /> </p></div>');
//check element as active
tracker[c1-1] = 1;
//if all element is > 0, disable the deleteButton.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
//alert(c1);
return false;
}
};
$(document).on('click', '#delete-spotlight', function() {
$(this).parent().parent().remove(); //remove the field.
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr("disabled"); //reset add button.
//Get the name, and parse to get the ID.
var deleteButtonName = this.name;
var stringDeleteButton = deleteButtonName.split("_").pop();
var deleteButtonID = parseInt(stringDeleteButton);
tracker[deleteButtonID-1] = 0; //reset element
//alert(tracker);
});
});
</script>
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance = $old_instance;
$instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);
$instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);
$increment = 1;
while ( $increment <= 2 ){
//increment variables
$increment_image_link = 'spotlight_image_link' . $increment;
$increment_add_image = 'spotlight_add_image' . $increment;
$increment_image_preview = 'spotlight_image_preview' . $increment;
$increment_description = 'spotlight_description' . $increment;
$increment_name = 'spotlight_name' . $increment;
$increment_link = 'spotlight_link' . $increment;
$instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );
$instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );
$instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);
$instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );
$instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );
$instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );
$increment++;
}
$starter = 1;
$num = 1;
return $instance;
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
```
**Quick Note:**
I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. |
257,451 | <p>I have my blogs on <code>wordpress.com</code> (e.g. <code>test.wordpress.com</code>). I want to migrate all those blogs to my self hosted WordPress website. Is this possible?</p>
<p>Is there any plugin in WordPress or do I need to develop any API?</p>
| [
{
"answer_id": 257415,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Widget forms are tricky for JS manipulation. In general you should never use IDs to detect elements in the form, but a combination of classes and <code>find()</code>, <code>parent()</code> etc.</p>\n\n<p>The reason is that there might be more than one form on the HTML page. For sure on the widget admin page there is a \"template\" form that is not displayed and IIRC is used to generate the form for a new widget. This means that there will be at least two element with the same ID, and an attempt to access them by DOM APIs will not give a consistent result.</p>\n"
},
{
"answer_id": 258297,
"author": "Sengngy Kouch",
"author_id": 113869,
"author_profile": "https://wordpress.stackexchange.com/users/113869",
"pm_score": 3,
"selected": true,
"text": "<p>Thank you <strong>Dave Romsey</strong> and <strong>Mark Kaplun</strong> for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.</p>\n\n<p><strong>Solution:</strong> </p>\n\n<p>We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called \"spotlight_image_link1, spotlight_image_link2, etc\". Then in the \"form function\" give their id using php code. Please read my code below for more information.</p>\n\n<p><strong>What can my solution do?</strong> </p>\n\n<p>Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read. </p>\n\n<p><strong>Here what it looks like:</strong> \n<a href=\"https://i.stack.imgur.com/Z6oZD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z6oZD.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Logic behind the scene:</strong> </p>\n\n<ul>\n<li>whenever the \"Click me!\" button is clicked, a spotlight will be added.</li>\n<li>There is a tracker array called \"tracker\" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the \"Click me!\" button.</li>\n<li>When the \"delete spotlight\" is clicked, remove that specific spotlight, and re-enable the \"Click me!\" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.</li>\n<li>The spotlight is saved only if and only if the input is not empty. That condition is in the \"while\" loop of the \"form\" function.</li>\n</ul>\n\n<p><strong>Limitation:</strong></p>\n\n<p>As of now, whenever, we clicked \"Save\", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet. </p>\n\n<p><strong>Source code:</strong> </p>\n\n<ul>\n<li>As of WordPress 4.7.2, it works without any error.</li>\n<li>Put all the source code into \"repeat.php\" file in your plugin directory. If you don't know how, please google it.</li>\n</ul>\n\n<p><strong>repeat.php</strong></p>\n\n<pre><code> <?php\n/**\n * Plugin Name: Repeat Field\n *\n */\n\n class repeat_field_widget extends WP_Widget {\n\n /**\n * Sets up the widgets name etc\n */\n public function __construct() {\n $widget_ops = array(\n 'classname' => 'repeat_field_widget',\n 'description' => 'Repeat Field for Name input'\n );\n parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );\n $tracker1;\n }\n\n /**\n * Outputs the content of the widget\n *\n * @param array $args\n * @param array $instance\n */\n public function widget( $args, $instance ) {\n // outputs the content of the widget\n $spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';\n $spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';\n\n /**============== Spotlight 1 =========================*/\n $spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';\n $spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';\n $spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';\n $spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';\n $spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';\n $spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';\n\n /**============== Spotlight 2 =========================*/\n $spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';\n $spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';\n $spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';\n $spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';\n $spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';\n $spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';\n }\n\n /**\n * Outputs the options form on admin\n *\n * @param array $instance The widget options\n */\n public function form( $instance ) {\n // outputs the options form on admin\n $instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',\n 'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));\n\n //Create Add and delete button\n $spotlight_add_row = $instance['spotlight_add_row'];\n $spotlight_row_appender = $instance['spotlight_row_appender'];\n\n /**================== Spotlight 1 ==============*/\n $spotlight_image_link1 = $instance['spotlight_image_link1'];\n $spotlight_add_image1 = $instance['spotlight_add_image1'];\n $spotlight_image_preview1 = $instance['spotlight_image_preview1'];\n $spotlight_name1 = $instance['spotlight_name1'];\n $spotlight_description1 = $instance['spotlight_description1'];\n $spotlight_link1 = $instance['spotlight_link1'];\n\n /**================== Spotlight 2 ==============*/\n $spotlight_image_link2 = $instance['spotlight_image_link2'];\n $spotlight_add_image2 = $instance['spotlight_add_image2'];\n $spotlight_image_preview2 = $instance['spotlight_image_preview2'];\n $spotlight_name2 = $instance['spotlight_name2'];\n $spotlight_description2 = $instance['spotlight_description2'];\n $spotlight_link2 = $instance['spotlight_link2'];\n\n $starter = 1; //Store which number to continue adding spotlight.\n $num = 1;\n $max_spotlight = 2; //number of spotlight allowed.\n static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.\n\n while($num <= $max_spotlight){\n $tempImage = 'spotlight_image_link' . $num;\n\n if ($$tempImage != ''){\n $starter++;\n $tracker[$num - 1] = 1;\n?>\n <!-- Image input -->\n <div>\n <p class=\"spotlight-para\">Spotlight <?php echo $num; ?></p>\n <p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->\n <label for=\"<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>\"><?php esc_attr_e( 'Image\\'s link:', 'text_domain' ); ?></label>\n <input\n class=\"widefat\"\n id=\"<?php echo $this->get_field_id($tempImage); ?>\"\n name=\"<?php echo $this->get_field_name($tempImage); ?>\"\n type=\"text\"\n value=\"<?php echo esc_attr($$tempImage); ?>\"\n />\n <input style=\"float:right;\" id=\"delete-spotlight\" name=\"<?php echo $tempDeleteName; ?>\" type=\"button\" value=\"Delete Spotlight\" class=\"button\"/>\n <br />\n </p>\n </div>\n<?php\n }\n $num++;\n }\n $id_prefix = $this->get_field_id(''); //get the widget prefix id.\n?>\n <span id=\"<?php echo $this->get_field_id('spotlight_row_appender'); ?>\"> </span>\n <div>\n <br />\n <input\n class=\"button\"\n type=\"button\"\n id=\"<?php echo $this->get_field_id('spotlight_add_row'); ?>\"\n value=\"Click Me!\"\n onclick=\"repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;\"\n />\n </div>\n\n <script>\n jQuery(document).ready(function($){\n var tracker = <?php echo json_encode($tracker); ?>;\n var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.\n\n //disbale add button when reaches max spotlight.\n if(tracker.every(x => x > 0)){\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr(\"disabled\",true);\n }\n\n repeater = {\n //TRY to mass Number into this function........\n uploader :function(widget_id, widget_id_string){\n //Find the non active element\n var i;\n for (i = 0; i < <?php echo $max_spotlight; ?>; i++){\n if ( tracker[i] == 0){\n c1 = i;\n break;\n }\n }\n c1++;\n //alert(c1);\n\n\n\n $(\"#\" + widget_id_string + \"spotlight_row_appender\").append('<div> <p class=\"spotlight-para\">Spotlight '+c1+'</p><p> <label for=\"<?php echo esc_attr( $this->get_field_id( \"spotlight_image_link'+c1+'\")); ?>\"><?php esc_attr_e( 'Image\\'s link:', 'text_domain' ); ?></label> <input class=\"widefat\" id=\"<?php echo $this->get_field_id(\"spotlight_image_link'+c1+'\"); ?>\" name=\"<?php echo $this->get_field_name(\"spotlight_image_link'+c1+'\"); ?>\" type=\"text\" value=\"\" /> <input style=\"float:right;\"id=\"delete-spotlight\" name=\"deletespotlight_'+c1+'\" type=\"button\" value=\"Delete Spotlight\" class=\"button\"/><br /> </p></div>');\n //check element as active\n tracker[c1-1] = 1;\n\n //if all element is > 0, disable the deleteButton.\n if(tracker.every(x => x > 0)){\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr(\"disabled\",true);\n }\n //alert(c1);\n return false;\n }\n };\n\n $(document).on('click', '#delete-spotlight', function() {\n\n $(this).parent().parent().remove(); //remove the field.\n $('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr(\"disabled\"); //reset add button.\n\n //Get the name, and parse to get the ID.\n var deleteButtonName = this.name;\n var stringDeleteButton = deleteButtonName.split(\"_\").pop();\n var deleteButtonID = parseInt(stringDeleteButton);\n\n tracker[deleteButtonID-1] = 0; //reset element\n //alert(tracker);\n });\n\n });\n </script>\n <?php\n }\n\n /**\n * Processing widget options on save\n *\n * @param array $new_instance The new options\n * @param array $old_instance The previous options\n */\n public function update( $new_instance, $old_instance ) {\n // processes widget options to be saved\n $instance = $old_instance;\n $instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);\n $instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);\n\n $increment = 1;\n while ( $increment <= 2 ){\n //increment variables\n $increment_image_link = 'spotlight_image_link' . $increment;\n $increment_add_image = 'spotlight_add_image' . $increment;\n $increment_image_preview = 'spotlight_image_preview' . $increment;\n $increment_description = 'spotlight_description' . $increment;\n $increment_name = 'spotlight_name' . $increment;\n $increment_link = 'spotlight_link' . $increment;\n\n $instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );\n $instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );\n $instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);\n $instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );\n $instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );\n $instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );\n\n $increment++;\n }\n $starter = 1;\n $num = 1;\n\n return $instance;\n }\n}\n\n\nfunction register_repeat_field_widget() {\n register_widget( 'repeat_field_widget' );\n}\nadd_action( 'widgets_init', 'register_repeat_field_widget' );\n</code></pre>\n\n<p><strong>Quick Note:</strong></p>\n\n<p>I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. </p>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257451",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113898/"
]
| I have my blogs on `wordpress.com` (e.g. `test.wordpress.com`). I want to migrate all those blogs to my self hosted WordPress website. Is this possible?
Is there any plugin in WordPress or do I need to develop any API? | Thank you **Dave Romsey** and **Mark Kaplun** for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.
**Solution:**
We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called "spotlight\_image\_link1, spotlight\_image\_link2, etc". Then in the "form function" give their id using php code. Please read my code below for more information.
**What can my solution do?**
Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read.
**Here what it looks like:**
[](https://i.stack.imgur.com/Z6oZD.png)
**Logic behind the scene:**
* whenever the "Click me!" button is clicked, a spotlight will be added.
* There is a tracker array called "tracker" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the "Click me!" button.
* When the "delete spotlight" is clicked, remove that specific spotlight, and re-enable the "Click me!" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.
* The spotlight is saved only if and only if the input is not empty. That condition is in the "while" loop of the "form" function.
**Limitation:**
As of now, whenever, we clicked "Save", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet.
**Source code:**
* As of WordPress 4.7.2, it works without any error.
* Put all the source code into "repeat.php" file in your plugin directory. If you don't know how, please google it.
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input'
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
$tracker1;
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
$spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';
$spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';
/**============== Spotlight 1 =========================*/
$spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';
$spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';
$spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';
$spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';
$spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';
$spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';
/**============== Spotlight 2 =========================*/
$spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';
$spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';
$spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';
$spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';
$spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';
$spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
$instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',
'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));
//Create Add and delete button
$spotlight_add_row = $instance['spotlight_add_row'];
$spotlight_row_appender = $instance['spotlight_row_appender'];
/**================== Spotlight 1 ==============*/
$spotlight_image_link1 = $instance['spotlight_image_link1'];
$spotlight_add_image1 = $instance['spotlight_add_image1'];
$spotlight_image_preview1 = $instance['spotlight_image_preview1'];
$spotlight_name1 = $instance['spotlight_name1'];
$spotlight_description1 = $instance['spotlight_description1'];
$spotlight_link1 = $instance['spotlight_link1'];
/**================== Spotlight 2 ==============*/
$spotlight_image_link2 = $instance['spotlight_image_link2'];
$spotlight_add_image2 = $instance['spotlight_add_image2'];
$spotlight_image_preview2 = $instance['spotlight_image_preview2'];
$spotlight_name2 = $instance['spotlight_name2'];
$spotlight_description2 = $instance['spotlight_description2'];
$spotlight_link2 = $instance['spotlight_link2'];
$starter = 1; //Store which number to continue adding spotlight.
$num = 1;
$max_spotlight = 2; //number of spotlight allowed.
static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.
while($num <= $max_spotlight){
$tempImage = 'spotlight_image_link' . $num;
if ($$tempImage != ''){
$starter++;
$tracker[$num - 1] = 1;
?>
<!-- Image input -->
<div>
<p class="spotlight-para">Spotlight <?php echo $num; ?></p>
<p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->
<label for="<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label>
<input
class="widefat"
id="<?php echo $this->get_field_id($tempImage); ?>"
name="<?php echo $this->get_field_name($tempImage); ?>"
type="text"
value="<?php echo esc_attr($$tempImage); ?>"
/>
<input style="float:right;" id="delete-spotlight" name="<?php echo $tempDeleteName; ?>" type="button" value="Delete Spotlight" class="button"/>
<br />
</p>
</div>
<?php
}
$num++;
}
$id_prefix = $this->get_field_id(''); //get the widget prefix id.
?>
<span id="<?php echo $this->get_field_id('spotlight_row_appender'); ?>"> </span>
<div>
<br />
<input
class="button"
type="button"
id="<?php echo $this->get_field_id('spotlight_add_row'); ?>"
value="Click Me!"
onclick="repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
/>
</div>
<script>
jQuery(document).ready(function($){
var tracker = <?php echo json_encode($tracker); ?>;
var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.
//disbale add button when reaches max spotlight.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
repeater = {
//TRY to mass Number into this function........
uploader :function(widget_id, widget_id_string){
//Find the non active element
var i;
for (i = 0; i < <?php echo $max_spotlight; ?>; i++){
if ( tracker[i] == 0){
c1 = i;
break;
}
}
c1++;
//alert(c1);
$("#" + widget_id_string + "spotlight_row_appender").append('<div> <p class="spotlight-para">Spotlight '+c1+'</p><p> <label for="<?php echo esc_attr( $this->get_field_id( "spotlight_image_link'+c1+'")); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id("spotlight_image_link'+c1+'"); ?>" name="<?php echo $this->get_field_name("spotlight_image_link'+c1+'"); ?>" type="text" value="" /> <input style="float:right;"id="delete-spotlight" name="deletespotlight_'+c1+'" type="button" value="Delete Spotlight" class="button"/><br /> </p></div>');
//check element as active
tracker[c1-1] = 1;
//if all element is > 0, disable the deleteButton.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
//alert(c1);
return false;
}
};
$(document).on('click', '#delete-spotlight', function() {
$(this).parent().parent().remove(); //remove the field.
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr("disabled"); //reset add button.
//Get the name, and parse to get the ID.
var deleteButtonName = this.name;
var stringDeleteButton = deleteButtonName.split("_").pop();
var deleteButtonID = parseInt(stringDeleteButton);
tracker[deleteButtonID-1] = 0; //reset element
//alert(tracker);
});
});
</script>
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance = $old_instance;
$instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);
$instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);
$increment = 1;
while ( $increment <= 2 ){
//increment variables
$increment_image_link = 'spotlight_image_link' . $increment;
$increment_add_image = 'spotlight_add_image' . $increment;
$increment_image_preview = 'spotlight_image_preview' . $increment;
$increment_description = 'spotlight_description' . $increment;
$increment_name = 'spotlight_name' . $increment;
$increment_link = 'spotlight_link' . $increment;
$instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );
$instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );
$instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);
$instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );
$instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );
$instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );
$increment++;
}
$starter = 1;
$num = 1;
return $instance;
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
```
**Quick Note:**
I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. |
257,478 | <p>How to get Custom Post ID by adding code to child theme's function. The following code works fine for the regular post, but can't figure out for the custom post types.</p>
<pre><code>add_filter( 'manage_posts_columns', 'revealid_add_id_column', 5 );
add_action( 'manage_posts_custom_column', 'revealid_id_column_content', 5, 2 );
function revealid_add_id_column( $columns ) {
$columns['revealid_id'] = 'ID';
return $columns;
}
function revealid_id_column_content( $column, $id ) {
if( 'revealid_id' == $column ) {
echo $id;
}
}
</code></pre>
| [
{
"answer_id": 257479,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<pre><code>add_action( 'manage_posts_custom_column', 'id_data' );\nadd_filter( 'manage_posts_columns', 'id_column' );\nfunction id_column( $defaults ) {\n $defaults['id'] = 'ID';\n return $defaults;\n}\nfunction id_data( $column_name ) {\n global $post;\n switch ( $column_name ) {\n case 'id':\n echo $post->ID;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257531,
"author": "Laxmana",
"author_id": 40948,
"author_profile": "https://wordpress.stackexchange.com/users/40948",
"pm_score": 0,
"selected": false,
"text": "<p>For custom post types there are the corresponding filters <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\"><code>manage_{$post_type}_posts_columns</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\"><code>manage_{$post_type}_posts_custom_column</code></a> where <code>{$post_type}</code> is your custom post name (<code>$post_type</code> variable in <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\"><code>register_post_type</code></a>).</p>\n\n<p>I assume, as you said in comments, that your custom post type is called <code>estate_property</code>.</p>\n\n<p>So:</p>\n\n<pre><code>add_filter( 'manage_estate_property_posts_columns', 'revealid_add_id_column', 5 );\nadd_action( 'manage_estate_property_posts_custom_column', 'revealid_id_column_content', 5, 2 );\n\nfunction revealid_add_id_column( $columns ) {\n $columns['revealid_id'] = 'ID';\n return $columns;\n}\n\nfunction revealid_id_column_content( $column, $id ) {\n if( 'revealid_id' == $column ) {\n echo $id;\n }\n}\n</code></pre>\n\n<p>This will work only for your custom post type. If you want to support multiple custom types read the doc of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column\" rel=\"nofollow noreferrer\">manage_posts_custom_column</a>.</p>\n\n<p>From <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\">WordPress Codex</a>: Note that if the custom post type has <code>'hierarchical' => true</code>, then the correct action hook to use is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_pages_custom_column\" rel=\"nofollow noreferrer\"><code>manage_pages_custom_column</code></a>.</p>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93692/"
]
| How to get Custom Post ID by adding code to child theme's function. The following code works fine for the regular post, but can't figure out for the custom post types.
```
add_filter( 'manage_posts_columns', 'revealid_add_id_column', 5 );
add_action( 'manage_posts_custom_column', 'revealid_id_column_content', 5, 2 );
function revealid_add_id_column( $columns ) {
$columns['revealid_id'] = 'ID';
return $columns;
}
function revealid_id_column_content( $column, $id ) {
if( 'revealid_id' == $column ) {
echo $id;
}
}
``` | ```
add_action( 'manage_posts_custom_column', 'id_data' );
add_filter( 'manage_posts_columns', 'id_column' );
function id_column( $defaults ) {
$defaults['id'] = 'ID';
return $defaults;
}
function id_data( $column_name ) {
global $post;
switch ( $column_name ) {
case 'id':
echo $post->ID;
}
}
``` |
257,482 | <p>I am creating a WordPress Plugin for WordPress directory.</p>
<p>How can I get <code>the_content()</code> after applying all the shortcodes that are presents in <code>the_content</code>?</p>
<p>Let me explain:</p>
<p>My plugin will be used in multiple themes and websites; and users will add some shortcodes in their posts or pages. I want my plugin to work after these shortcodes are parsed, and then use the content for my plugin as input.</p>
| [
{
"answer_id": 257479,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<pre><code>add_action( 'manage_posts_custom_column', 'id_data' );\nadd_filter( 'manage_posts_columns', 'id_column' );\nfunction id_column( $defaults ) {\n $defaults['id'] = 'ID';\n return $defaults;\n}\nfunction id_data( $column_name ) {\n global $post;\n switch ( $column_name ) {\n case 'id':\n echo $post->ID;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257531,
"author": "Laxmana",
"author_id": 40948,
"author_profile": "https://wordpress.stackexchange.com/users/40948",
"pm_score": 0,
"selected": false,
"text": "<p>For custom post types there are the corresponding filters <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\"><code>manage_{$post_type}_posts_columns</code></a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\"><code>manage_{$post_type}_posts_custom_column</code></a> where <code>{$post_type}</code> is your custom post name (<code>$post_type</code> variable in <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\"><code>register_post_type</code></a>).</p>\n\n<p>I assume, as you said in comments, that your custom post type is called <code>estate_property</code>.</p>\n\n<p>So:</p>\n\n<pre><code>add_filter( 'manage_estate_property_posts_columns', 'revealid_add_id_column', 5 );\nadd_action( 'manage_estate_property_posts_custom_column', 'revealid_id_column_content', 5, 2 );\n\nfunction revealid_add_id_column( $columns ) {\n $columns['revealid_id'] = 'ID';\n return $columns;\n}\n\nfunction revealid_id_column_content( $column, $id ) {\n if( 'revealid_id' == $column ) {\n echo $id;\n }\n}\n</code></pre>\n\n<p>This will work only for your custom post type. If you want to support multiple custom types read the doc of <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column\" rel=\"nofollow noreferrer\">manage_posts_custom_column</a>.</p>\n\n<p>From <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_$post_type_posts_custom_column\" rel=\"nofollow noreferrer\">WordPress Codex</a>: Note that if the custom post type has <code>'hierarchical' => true</code>, then the correct action hook to use is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/manage_pages_custom_column\" rel=\"nofollow noreferrer\"><code>manage_pages_custom_column</code></a>.</p>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113920/"
]
| I am creating a WordPress Plugin for WordPress directory.
How can I get `the_content()` after applying all the shortcodes that are presents in `the_content`?
Let me explain:
My plugin will be used in multiple themes and websites; and users will add some shortcodes in their posts or pages. I want my plugin to work after these shortcodes are parsed, and then use the content for my plugin as input. | ```
add_action( 'manage_posts_custom_column', 'id_data' );
add_filter( 'manage_posts_columns', 'id_column' );
function id_column( $defaults ) {
$defaults['id'] = 'ID';
return $defaults;
}
function id_data( $column_name ) {
global $post;
switch ( $column_name ) {
case 'id':
echo $post->ID;
}
}
``` |
257,483 | <p>Here is my script : </p>
<pre><code>$my_post = array(
'post_title' => "post test",
'post_date' => current_time('mysql'),
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
$post_id= wp_insert_post($my_post);
var_dump($post_id);
</code></pre>
| [
{
"answer_id": 257487,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the date param or use the right format for the time stamp, like <code>date('Y-m-d H:i:s'),</code> But it is not necessary, WP use the current timestamp on the insert post time.</p>\n"
},
{
"answer_id": 257494,
"author": "Esar-ul-haq Qasmi",
"author_id": 101704,
"author_profile": "https://wordpress.stackexchange.com/users/101704",
"pm_score": 0,
"selected": false,
"text": "<p>The date param is wrong. the format for the date should match the wp standards for the post. The below snippet works fine. </p>\n\n<pre><code>$my_post = array(\n 'post_title' => \"post test\",\n 'post_date' =>date('Y-m-d H:i:s'),\n 'post_content' => 'This is my post.',\n 'post_status' => 'publish', \n 'post_author' => 1,\n 'post_category' => array(1)\n\n ); \n $post_id= wp_insert_post($my_post); \n var_dump($post_id);\n</code></pre>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113921/"
]
| Here is my script :
```
$my_post = array(
'post_title' => "post test",
'post_date' => current_time('mysql'),
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
$post_id= wp_insert_post($my_post);
var_dump($post_id);
``` | Remove the date param or use the right format for the time stamp, like `date('Y-m-d H:i:s'),` But it is not necessary, WP use the current timestamp on the insert post time. |
257,489 | <p>I've been tasked to move a website into a new domain, and I've encontered this weird issue.<br>
On the homepage, I always see these:</p>
<blockquote>
<p>Notice: Constant AUTOSAVE_INTERVAL already defined in /home/gturnat/public_html/wp-config.php on line 99</p>
<p>Notice: Constant WP_POST_REVISIONS already defined in /home/gturnat/public_html/wp-config.php on line 100</p>
</blockquote>
<hr>
<p>What I have tried:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/q/158075/89236">Notice: Constant WP_POST_REVISIONS already defined</a> suggests commenting the constants on <code>default-constants.php</code>, but it doesn't work.</li>
<li>Settings <code>display_errors</code> to <code>0</code>, <code>'0'</code> or <code>'Off'</code> does nothing.</li>
<li>Running <code>error_reporting(0)</code> will still display the errors.</li>
<li>Creating a <code>mu-plugin</code> (<a href="https://stackoverflow.com/a/27997023">As suggested on How can I stop PHP notices from appearing in wordpress?</a>).<br>
Nothing happens and the plugin isn't even loaded.<br>
The errors still keep showing up.</li>
<li>Tried to comment out the lines in <code>wp-config.php</code>, but didn't work. The notices are still there.</li>
<li>Removed the lines <strong>entirelly</strong> and moved them around <code>wp-config.php</code>, but the warnings insist it is on line 99 and 100.<br>
Causing a syntax error inside <code>wp-config.php</code> does lead to an error being logged, which means that the file isn't cached.</li>
<li>Tried to enable and disable the debug mode, set <code>display_errors</code> to <code>false</code>, <code>0</code>, <code>'0'</code> and <code>'Off'</code>, but doesn't work.</li>
<li>Ran <code>grep -1R WP_POST_REVISIONS *</code> and <code>grep -1R AUTOSAVE_INTERVAL *</code> with the following result:
<blockquote>
<p>root@webtest:# grep -lR WP_POST_REVISIONS *<br>
wp-config.php<br>
wp-includes/default-constants.php<br>
wp-includes/revision.php<br>
root@webtest:# grep -lR AUTOSAVE_INTERVAL *<br>
wp-config.php<br>
wp-includes/script-loader.php<br>
wp-includes/default-constants.php<br>
wp-includes/class-wp-customize-manager.php</p>
</blockquote></li>
</ul>
<p>I really am out of any other idea to try.</p>
<hr>
<p>I'm using Wordpress 4.7.2, running on PHP 5.4 with the following modules loaded:</p>
<p><a href="https://i.stack.imgur.com/6kH47.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6kH47.png" alt="loaded modules"></a></p>
<p>There is no op-cache working in the server. Just those options.</p>
<p>PHP was configured with the following options:</p>
<pre><code>'./configure' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--target=x86_64-redhat-linux-gnu' '--program-prefix=' '--prefix=/opt/alt/php54' '--exec-prefix=/opt/alt/php54' '--bindir=/opt/alt/php54/usr/bin' '--sbindir=/opt/alt/php54/usr/sbin' '--sysconfdir=/opt/alt/php54/etc' '--datadir=/opt/alt/php54/usr/share' '--includedir=/opt/alt/php54/usr/include' '--libdir=/opt/alt/php54/usr/lib64' '--libexecdir=/opt/alt/php54/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/opt/alt/php54/usr/share/man' '--infodir=/opt/alt/php54/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib64' '--with-config-file-path=/opt/alt/php54/etc' '--with-config-file-scan-dir=/opt/alt/php54/link/conf' '--with-exec-dir=/usr/bin' '--with-layout=GNU' '--disable-debug' '--disable-rpath' '--without-pear' '--without-gdbm' '--with-pic' '--with-zlib' '--with-bz2' '--with-gettext' '--with-gmp' '--with-iconv' '--with-openssl' '--with-kerberos' '--with-mhash' '--with-readline' '--with-pcre-regex=/opt/alt/pcre/usr' '--with-libxml-dir=/opt/alt/libxml2/usr' '--with-curl=/opt/alt/curlssl/usr' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-shmop' '--enable-calendar' '--enable-xml' '--enable-force-cgi-redirect' '--enable-fastcgi' '--enable-pcntl' '--enable-bcmath=shared' '--enable-dba=shared' '--with-db4=/usr' '--enable-dbx=shared,/usr' '--enable-dom=shared' '--enable-fileinfo=shared' '--enable-intl=shared' '--enable-json=shared' '--enable-mbstring=shared' '--enable-mbregex' '--enable-pdo=shared' '--enable-phar=shared' '--enable-posix=shared' '--enable-soap=shared' '--enable-sockets=shared' '--enable-sqlite3=shared,/opt/alt/sqlite/usr' '--enable-sysvsem=shared' '--enable-sysvshm=shared' '--enable-sysvmsg=shared' '--enable-wddx=shared' '--enable-xmlreader=shared' '--enable-xmlwriter=shared' '--enable-zip=shared' '--with-gd=shared' '--enable-gd-native-ttf' '--with-jpeg-dir=/usr' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--with-xpm-dir=/usr' '--with-t1lib=/opt/alt/t1lib/usr' '--with-imap=shared' '--with-imap-ssl' '--with-xmlrpc=shared' '--with-ldap=shared' '--with-ldap-sasl' '--with-pgsql=shared' '--with-snmp=shared,/usr' '--enable-ucd-snmp-hack' '--with-xsl=shared,/usr' '--with-pdo-odbc=shared,unixODBC,/usr' '--with-pdo-pgsql=shared,/usr' '--with-pdo-sqlite=shared,/opt/alt/sqlite/usr' '--with-mssql=shared,/opt/alt/freetds/usr' '--with-interbase=shared,/usr' '--with-pdo-firebird=shared,/usr' '--with-pdo-dblib=shared,/opt/alt/freetds/usr' '--with-mcrypt=shared,/usr' '--with-tidy=shared,/usr' '--with-recode=shared,/usr' '--with-enchant=shared,/usr' '--with-pspell=shared' '--with-unixODBC=shared,/usr' '--with-icu-dir=/opt/alt/libicu/usr' '--with-sybase-ct=shared,/opt/alt/freetds/usr'
</code></pre>
<hr>
<p>As a testing point, I tried to run it on PHP 5.6, with the same results, with the following modules:</p>
<p><a href="https://i.stack.imgur.com/ezCyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ezCyR.png" alt="php 5.6"></a></p>
| [
{
"answer_id": 257487,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the date param or use the right format for the time stamp, like <code>date('Y-m-d H:i:s'),</code> But it is not necessary, WP use the current timestamp on the insert post time.</p>\n"
},
{
"answer_id": 257494,
"author": "Esar-ul-haq Qasmi",
"author_id": 101704,
"author_profile": "https://wordpress.stackexchange.com/users/101704",
"pm_score": 0,
"selected": false,
"text": "<p>The date param is wrong. the format for the date should match the wp standards for the post. The below snippet works fine. </p>\n\n<pre><code>$my_post = array(\n 'post_title' => \"post test\",\n 'post_date' =>date('Y-m-d H:i:s'),\n 'post_content' => 'This is my post.',\n 'post_status' => 'publish', \n 'post_author' => 1,\n 'post_category' => array(1)\n\n ); \n $post_id= wp_insert_post($my_post); \n var_dump($post_id);\n</code></pre>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89236/"
]
| I've been tasked to move a website into a new domain, and I've encontered this weird issue.
On the homepage, I always see these:
>
> Notice: Constant AUTOSAVE\_INTERVAL already defined in /home/gturnat/public\_html/wp-config.php on line 99
>
>
> Notice: Constant WP\_POST\_REVISIONS already defined in /home/gturnat/public\_html/wp-config.php on line 100
>
>
>
---
What I have tried:
* [Notice: Constant WP\_POST\_REVISIONS already defined](https://wordpress.stackexchange.com/q/158075/89236) suggests commenting the constants on `default-constants.php`, but it doesn't work.
* Settings `display_errors` to `0`, `'0'` or `'Off'` does nothing.
* Running `error_reporting(0)` will still display the errors.
* Creating a `mu-plugin` ([As suggested on How can I stop PHP notices from appearing in wordpress?](https://stackoverflow.com/a/27997023)).
Nothing happens and the plugin isn't even loaded.
The errors still keep showing up.
* Tried to comment out the lines in `wp-config.php`, but didn't work. The notices are still there.
* Removed the lines **entirelly** and moved them around `wp-config.php`, but the warnings insist it is on line 99 and 100.
Causing a syntax error inside `wp-config.php` does lead to an error being logged, which means that the file isn't cached.
* Tried to enable and disable the debug mode, set `display_errors` to `false`, `0`, `'0'` and `'Off'`, but doesn't work.
* Ran `grep -1R WP_POST_REVISIONS *` and `grep -1R AUTOSAVE_INTERVAL *` with the following result:
>
> root@webtest:# grep -lR WP\_POST\_REVISIONS \*
>
> wp-config.php
>
> wp-includes/default-constants.php
>
> wp-includes/revision.php
>
> root@webtest:# grep -lR AUTOSAVE\_INTERVAL \*
>
> wp-config.php
>
> wp-includes/script-loader.php
>
> wp-includes/default-constants.php
>
> wp-includes/class-wp-customize-manager.php
>
>
>
I really am out of any other idea to try.
---
I'm using Wordpress 4.7.2, running on PHP 5.4 with the following modules loaded:
[](https://i.stack.imgur.com/6kH47.png)
There is no op-cache working in the server. Just those options.
PHP was configured with the following options:
```
'./configure' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--target=x86_64-redhat-linux-gnu' '--program-prefix=' '--prefix=/opt/alt/php54' '--exec-prefix=/opt/alt/php54' '--bindir=/opt/alt/php54/usr/bin' '--sbindir=/opt/alt/php54/usr/sbin' '--sysconfdir=/opt/alt/php54/etc' '--datadir=/opt/alt/php54/usr/share' '--includedir=/opt/alt/php54/usr/include' '--libdir=/opt/alt/php54/usr/lib64' '--libexecdir=/opt/alt/php54/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/opt/alt/php54/usr/share/man' '--infodir=/opt/alt/php54/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib64' '--with-config-file-path=/opt/alt/php54/etc' '--with-config-file-scan-dir=/opt/alt/php54/link/conf' '--with-exec-dir=/usr/bin' '--with-layout=GNU' '--disable-debug' '--disable-rpath' '--without-pear' '--without-gdbm' '--with-pic' '--with-zlib' '--with-bz2' '--with-gettext' '--with-gmp' '--with-iconv' '--with-openssl' '--with-kerberos' '--with-mhash' '--with-readline' '--with-pcre-regex=/opt/alt/pcre/usr' '--with-libxml-dir=/opt/alt/libxml2/usr' '--with-curl=/opt/alt/curlssl/usr' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-shmop' '--enable-calendar' '--enable-xml' '--enable-force-cgi-redirect' '--enable-fastcgi' '--enable-pcntl' '--enable-bcmath=shared' '--enable-dba=shared' '--with-db4=/usr' '--enable-dbx=shared,/usr' '--enable-dom=shared' '--enable-fileinfo=shared' '--enable-intl=shared' '--enable-json=shared' '--enable-mbstring=shared' '--enable-mbregex' '--enable-pdo=shared' '--enable-phar=shared' '--enable-posix=shared' '--enable-soap=shared' '--enable-sockets=shared' '--enable-sqlite3=shared,/opt/alt/sqlite/usr' '--enable-sysvsem=shared' '--enable-sysvshm=shared' '--enable-sysvmsg=shared' '--enable-wddx=shared' '--enable-xmlreader=shared' '--enable-xmlwriter=shared' '--enable-zip=shared' '--with-gd=shared' '--enable-gd-native-ttf' '--with-jpeg-dir=/usr' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--with-xpm-dir=/usr' '--with-t1lib=/opt/alt/t1lib/usr' '--with-imap=shared' '--with-imap-ssl' '--with-xmlrpc=shared' '--with-ldap=shared' '--with-ldap-sasl' '--with-pgsql=shared' '--with-snmp=shared,/usr' '--enable-ucd-snmp-hack' '--with-xsl=shared,/usr' '--with-pdo-odbc=shared,unixODBC,/usr' '--with-pdo-pgsql=shared,/usr' '--with-pdo-sqlite=shared,/opt/alt/sqlite/usr' '--with-mssql=shared,/opt/alt/freetds/usr' '--with-interbase=shared,/usr' '--with-pdo-firebird=shared,/usr' '--with-pdo-dblib=shared,/opt/alt/freetds/usr' '--with-mcrypt=shared,/usr' '--with-tidy=shared,/usr' '--with-recode=shared,/usr' '--with-enchant=shared,/usr' '--with-pspell=shared' '--with-unixODBC=shared,/usr' '--with-icu-dir=/opt/alt/libicu/usr' '--with-sybase-ct=shared,/opt/alt/freetds/usr'
```
---
As a testing point, I tried to run it on PHP 5.6, with the same results, with the following modules:
[](https://i.stack.imgur.com/ezCyR.png) | Remove the date param or use the right format for the time stamp, like `date('Y-m-d H:i:s'),` But it is not necessary, WP use the current timestamp on the insert post time. |
257,499 | <p>I'm using a function to filter the_title, adding a string onto the end, but would also like to return the original title, unfiltered on the same page. Is there a way to get the title without it being filtered? </p>
| [
{
"answer_id": 257501,
"author": "engelen",
"author_id": 40403,
"author_profile": "https://wordpress.stackexchange.com/users/40403",
"pm_score": 3,
"selected": true,
"text": "<p>There's a few ways to do this, but I would argue that the preferred way is, in general, fetching the <code>post_title</code> attribute from the post object. This does not depend on removing all filters for a certain function and adding them back later — the latter requires you to directly access the global <code>$wp_filter</code>.</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post\" rel=\"nofollow noreferrer\"><code>get_post</code></a> retrieves the post object for a post ID, and the post object, on construction, populates all post fields with the fields from the database, without applying any filtering.</p>\n\n<p>Thus, your code would simply be</p>\n\n<pre><code>$title = get_post( $post_id )->post_title;\n</code></pre>\n\n<p>If the post with ID <code>$post_id</code> is not guaranteed to exist, be sure to check whether the returned value from <code>get_post</code> is a post object.</p>\n\n<p>NB another approach is to use <code>get_post_field( 'post_title', $post_id )</code>, which by default only has the filter <code>'post_title'</code> applied to it (and not the <code>the_title</code> filter). However, as @PatJ kindly pointed out, using the optional <code>$context</code> parameter, you can get the raw value using the context <code>\"raw\"</code>:</p>\n\n<pre><code>get_post_field( 'post_title', $post_id, 'raw' );\n</code></pre>\n"
},
{
"answer_id": 257506,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 0,
"selected": false,
"text": "<p>You can create your own function, put this in <code>functions.php</code>:</p>\n\n<pre><code>function get_title_no_filters($post = 0){\n\n $post = get_post( $post );\n\n echo isset( $post->post_title ) ? $post->post_title : '';\n}\n</code></pre>\n\n<p>use it like this, just like the <code>get_the_title</code> WordPress offers:</p>\n\n<pre><code>get_title_no_filters();//inside a loop no need to send ID or post object\n</code></pre>\n\n<p>if you are not using it in a loop you can send an ID or a Post Object. This is the <code>raw</code> title no filters.</p>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
]
| I'm using a function to filter the\_title, adding a string onto the end, but would also like to return the original title, unfiltered on the same page. Is there a way to get the title without it being filtered? | There's a few ways to do this, but I would argue that the preferred way is, in general, fetching the `post_title` attribute from the post object. This does not depend on removing all filters for a certain function and adding them back later — the latter requires you to directly access the global `$wp_filter`.
[`get_post`](https://codex.wordpress.org/Function_Reference/get_post) retrieves the post object for a post ID, and the post object, on construction, populates all post fields with the fields from the database, without applying any filtering.
Thus, your code would simply be
```
$title = get_post( $post_id )->post_title;
```
If the post with ID `$post_id` is not guaranteed to exist, be sure to check whether the returned value from `get_post` is a post object.
NB another approach is to use `get_post_field( 'post_title', $post_id )`, which by default only has the filter `'post_title'` applied to it (and not the `the_title` filter). However, as @PatJ kindly pointed out, using the optional `$context` parameter, you can get the raw value using the context `"raw"`:
```
get_post_field( 'post_title', $post_id, 'raw' );
``` |
257,542 | <p>All I did was adding this in my functions.php file:</p>
<pre><code>function save_nb_image()
{
global $wpdb;
$id = $_POST['id'];
$file = wp_get_attachment_url($id);
if ( !is_wp_error($id) )
{
$meta = wp_generate_attachment_metadata($id, $file);
$meta = nb_image_crop($meta);
wp_update_attachment_metadata($id, $meta);
}
wp_die();
}
add_action( 'wp_ajax_nb-image-autofix', 'save_nb_image' );
</code></pre>
<p>Then I tried to call it from a custom button in image edit form. Something didn't worked because nothing happened.</p>
<p>Then little later when I went into the Media Library again, the images wouldn't load. Chrome Console log said something about problem with mixed content. I have pretty recently changed to SSL/https so I thought that might been the problem. Although it's strange that change for some weeks ago make this affect now. I have been in media library a lot of times after that change and everything has worked perfectly.</p>
<p>But anyway, IF there is a SSL problem, I added "SSL Insecure Content Fixer" plugin to let that clear out everything. And I ran that plugin and then went in to the media library again. The console errors was now gone. But the images is still not loading. There is just a load spinner going on forever.</p>
<p>I have also tried activate the debug mode from wp_config but there is no related errors.</p>
<p>I have also tried re-installing the Wordpress version from Dashboard > Updates.</p>
<p>I have also of course tried remove the code I mentioned above.</p>
<p>What is there else to try?</p>
<p><strong>Edit:</strong> I think it might be a database issue. Cause I even tried to remove all the files except /wp-content folder and wp-config.php file. And installed the older WP 4.4 version. Then went in and updated to latest version. After that: Still no images in grid view....</p>
<p><strong>Edit, 27 feb 2017:</strong> I have found out that <code>wp_get_attachment_url()</code> was the wrong function to use since I wanted the absolute path and not the URL. So the right function to use is <code>get_attached_file()</code>. When I used the <code>wp_get_attachment_url()</code> function the ajax was loading very long time and returned a lot of strange code that I suspect was the image on some kind of code format. After changing to <code>get_attached_file()</code> the loading was much faster and the functionality of everything I wanted with the code did work as expected. However, maybe something with the earlier code made a mess in the database causing the Grid Mode problem?</p>
| [
{
"answer_id": 257576,
"author": "Purple Haze Design Group",
"author_id": 113974,
"author_profile": "https://wordpress.stackexchange.com/users/113974",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue recently. I had moved over a theme with some plugin specific code in the functions.php. I forgot however to install said plugin. The grid view in the media gallery wouldn't load, but the list view would. </p>\n\n<p><strong>What Fixed It For Me</strong></p>\n\n<ul>\n<li>Remove plugin specific code from Functions file.</li>\n<li>Install proper plugin</li>\n<li>Add plugin specific code to Functions file.</li>\n</ul>\n\n<p>I'm not sure if that will work for you but maybe check your plugins.</p>\n"
},
{
"answer_id": 258141,
"author": "Peter Westerlund",
"author_id": 3216,
"author_profile": "https://wordpress.stackexchange.com/users/3216",
"pm_score": 2,
"selected": true,
"text": "<p>Problem is now solved. Thanks to user \"blobfolio\" <a href=\"https://core.trac.wordpress.org/ticket/39974#comment:2\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<blockquote>\n <p>It sounds like you may have corrupted the image metadata. Have you\n tried running a plugin like\n <a href=\"https://wordpress.org/plugins/force-regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/force-regenerate-thumbnails/</a> to\n regenerate the images/meta?</p>\n</blockquote>\n\n<p><strong>Solution:</strong></p>\n\n<p>So the solution is to force regenerate all the thumbnails. For example using the plugin mentioned above in the quote.</p>\n"
},
{
"answer_id": 368989,
"author": "Maulana Agung",
"author_id": 189971,
"author_profile": "https://wordpress.stackexchange.com/users/189971",
"pm_score": 0,
"selected": false,
"text": "<p>I had similar issue recently, after inspecting admin page the <code>admin-ajax.php</code> response contain non-json response. It is because my client adding extra code in <code>functions.php</code> that somehow append inline <code><style></style></code> to the <code>admin-ajax.php</code> response.</p>\n<p><strong>Solution:</strong> Check the <code>admin-ajax.php</code> response, if there are non-json return or invalid json return you should investigate where the extra ajax response come from.</p>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3216/"
]
| All I did was adding this in my functions.php file:
```
function save_nb_image()
{
global $wpdb;
$id = $_POST['id'];
$file = wp_get_attachment_url($id);
if ( !is_wp_error($id) )
{
$meta = wp_generate_attachment_metadata($id, $file);
$meta = nb_image_crop($meta);
wp_update_attachment_metadata($id, $meta);
}
wp_die();
}
add_action( 'wp_ajax_nb-image-autofix', 'save_nb_image' );
```
Then I tried to call it from a custom button in image edit form. Something didn't worked because nothing happened.
Then little later when I went into the Media Library again, the images wouldn't load. Chrome Console log said something about problem with mixed content. I have pretty recently changed to SSL/https so I thought that might been the problem. Although it's strange that change for some weeks ago make this affect now. I have been in media library a lot of times after that change and everything has worked perfectly.
But anyway, IF there is a SSL problem, I added "SSL Insecure Content Fixer" plugin to let that clear out everything. And I ran that plugin and then went in to the media library again. The console errors was now gone. But the images is still not loading. There is just a load spinner going on forever.
I have also tried activate the debug mode from wp\_config but there is no related errors.
I have also tried re-installing the Wordpress version from Dashboard > Updates.
I have also of course tried remove the code I mentioned above.
What is there else to try?
**Edit:** I think it might be a database issue. Cause I even tried to remove all the files except /wp-content folder and wp-config.php file. And installed the older WP 4.4 version. Then went in and updated to latest version. After that: Still no images in grid view....
**Edit, 27 feb 2017:** I have found out that `wp_get_attachment_url()` was the wrong function to use since I wanted the absolute path and not the URL. So the right function to use is `get_attached_file()`. When I used the `wp_get_attachment_url()` function the ajax was loading very long time and returned a lot of strange code that I suspect was the image on some kind of code format. After changing to `get_attached_file()` the loading was much faster and the functionality of everything I wanted with the code did work as expected. However, maybe something with the earlier code made a mess in the database causing the Grid Mode problem? | Problem is now solved. Thanks to user "blobfolio" [here](https://core.trac.wordpress.org/ticket/39974#comment:2):
>
> It sounds like you may have corrupted the image metadata. Have you
> tried running a plugin like
> <https://wordpress.org/plugins/force-regenerate-thumbnails/> to
> regenerate the images/meta?
>
>
>
**Solution:**
So the solution is to force regenerate all the thumbnails. For example using the plugin mentioned above in the quote. |
257,571 | <p>On my single.php page I am trying to create a function to give me a custom length excerpt of a specific post by ID.</p>
<p>Below are my two functions I am running.</p>
<pre><code>/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
</code></pre>
<p>What I'm using to call the function.</p>
<pre><code><?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
</code></pre>
<p>The issue I am running into is $post is giving me the previous post information, however, when I pass that into get_the_excerpt it returns the current post excerpt rather than the previous post excerpt.</p>
<p>EDIT</p>
<p>Changed function to this after several people told me I can just pass the $post_id to get_the_excerpt()</p>
<pre><code> /* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
</code></pre>
<p>Still no change.</p>
| [
{
"answer_id": 257572,
"author": "MaximOrlovsky",
"author_id": 15294,
"author_profile": "https://wordpress.stackexchange.com/users/15294",
"pm_score": 3,
"selected": true,
"text": "<p>Try this one</p>\n\n<pre><code>/* Change Excerpt length */\nfunction excerpt($num, $post_id) { // removed empty default value\n $limit = $num+1;\n $excerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));\n $excerpt = explode(' ', $excerpt, $limit);\n array_pop($excerpt);\n $excerpt = implode(\" \",$excerpt).\"&#8230\";\n echo $excerpt;\n}\n</code></pre>\n\n<p>Another solution - using <code>setup_postdata($post);</code> and <code>wp_reset_postdata();</code></p>\n\n<pre><code>function custom_get_the_excerpt($post_id) {\n global $post;\n $save_post = $post;\n $post = get_post($post_id);\n setup_postdata($post);\n $output = get_the_excerpt($post);\n wp_reset_postdata();\n $post = $save_post;\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 257579,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need to use custom CODE just to change excerpt length. There is a default WordPress filter for that: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/excerpt_length\" rel=\"nofollow noreferrer\"><code>excerpt_length</code></a>. You just need to use it.</p>\n\n<h1>To change to the same excerpt length every where on the theme</h1>\n\n<p>If you use the same excerpt length everywhere on your site, then just add the following CODE in your theme's <code>functions.php</code> file:</p>\n\n<pre><code>function my_custom_excerpt_length( $length ) {\n // set the number you want\n return 20;\n}\nadd_filter( 'excerpt_length', 'my_custom_excerpt_length', 999 );\n</code></pre>\n\n<p>and then in your template file (for example <code>single.php</code>), simply call:</p>\n\n<pre><code>echo get_the_excerpt( $post_id );\n</code></pre>\n\n<h1>To use different excerpt lengths on the theme</h1>\n\n<p>If you want to use different excerpt length on different places, then it makes sense to create a custom function so that you may call it easily. Even then you can just make use of WordPress supplied functions and filters. In this case, use the following functions in <code>functions.php</code> file:</p>\n\n<pre><code>function set_custom_excerpt_length( $length ) {\n global $custom_excerpt_length;\n if( ! isset( $custom_excerpt_length ) ) {\n return $length;\n }\n return $custom_excerpt_length;\n}\n\nfunction my_excerpt( $post_id = null, $length = 55 ) {\n global $custom_excerpt_length, $post;\n $custom_excerpt_length = $length;\n if( is_null( $post_id ) ) {\n $post_id = $post->ID;\n }\n add_filter( 'excerpt_length', 'set_custom_excerpt_length', 999 );\n echo get_the_excerpt( $post_id );\n remove_filter( 'excerpt_length', 'set_custom_excerpt_length', 999 );\n}\n</code></pre>\n\n<p>Then use it like so in your template file:</p>\n\n<pre><code>my_excerpt( $previous->ID, 30 );\n</code></pre>\n\n<p>You can of course use custom functions used by other answers, however, you'll miss out on WordPress default behaviour in that case.</p>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> If you are using <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">the loop</a> properly, you shouldn't have to call \n <code>wp_reset_postdata()</code> on every excerpt function call.</p>\n</blockquote>\n"
}
]
| 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112804/"
]
| On my single.php page I am trying to create a function to give me a custom length excerpt of a specific post by ID.
Below are my two functions I am running.
```
/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
What I'm using to call the function.
```
<?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
```
The issue I am running into is $post is giving me the previous post information, however, when I pass that into get\_the\_excerpt it returns the current post excerpt rather than the previous post excerpt.
EDIT
Changed function to this after several people told me I can just pass the $post\_id to get\_the\_excerpt()
```
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
Still no change. | Try this one
```
/* Change Excerpt length */
function excerpt($num, $post_id) { // removed empty default value
$limit = $num+1;
$excerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
$excerpt = explode(' ', $excerpt, $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
Another solution - using `setup_postdata($post);` and `wp_reset_postdata();`
```
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
setup_postdata($post);
$output = get_the_excerpt($post);
wp_reset_postdata();
$post = $save_post;
return $output;
}
``` |
257,586 | <p>I've always used @import for the css in my child-theme which i'm now told is bad practice.</p>
<p>What is the best way to set up a child theme going forward? The latest solution on the wordpress codex seems really complex / highly confusing?</p>
<p>There must be a way to do a relatively simple enqueue in my child-theme's functions.php surely?</p>
<p>Any help would be awesome. I feel completely lost / useless trying to find any succinct info on this.</p>
<p>Emily</p>
| [
{
"answer_id": 257588,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the specific code you're looking for, this can be found in the WordPress Codex <a href=\"https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme\" rel=\"nofollow noreferrer\">How to Create a Child Theme</a></p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n // This is the parent style handle name. Recommended to leave as it is.\n $parent_style = 'parent-style';\n\n wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()->get('Version')\n );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n\n<p><strong>Credits</strong> goes to WordPress Codex.</p>\n"
},
{
"answer_id": 257879,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p>The code that is in <a href=\"https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme\" rel=\"nofollow noreferrer\">codex</a> for queuing the style of the parent theme instead of using <code>@import</code>, is not well commented, so i will comment it more, so you have this:</p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n $parent_style = 'parent-style';\n wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');\n wp_enqueue_style('child-style', \n get_stylesheet_directory_uri() . '/style.css', \n array($parent_style), \n wp_get_theme()->get('Version')\n );\n}\nadd_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');\n?>\n</code></pre>\n\n<p>1.- line:</p>\n\n<pre><code>$parent_style = 'parent-style';\n</code></pre>\n\n<p>this is literally a string name that you are giving to the theme stylesheet, it will be the <code>$handle</code> of the stylesheet you are queuing, it can be what you want, by example <code>'divi-style'</code>, in the <code>HTML</code> it will be used as the <code>ID</code> like this <code><link rel=\"stylesheet\" id=\"divi-style\" ...</code></p>\n\n<p>2.- line:</p>\n\n<pre><code>wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');\n</code></pre>\n\n<p>its registering the stylesheet and queuing it, when its registering it, it will use the name of the first parameter in this case it will be <code>'parent-style'</code>, also its using <code>get_template_directory_uri()</code> to get the path to the <code>parent theme</code> stylesheet.</p>\n\n<p>3.- line:</p>\n\n<pre><code>wp_enqueue_style('child-style', \n get_stylesheet_directory_uri() . '/style.css', \n array($parent_style), \n wp_get_theme()->get('Version')\n );\n</code></pre>\n\n<p>this is registering and queuing the child theme stylesheet (the current theme stylesheet), this is the usual procedure for a theme, each parameter its already explained <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">here</a>, for the example:</p>\n\n<ul>\n<li><p><code>'child-style'</code> - this is the name of this stylesheet the <code>$handle</code></p></li>\n<li><p><code>get_stylesheet_directory_uri() . '/style.css'</code> - this is the path to\nthe stylesheet file.</p></li>\n<li><p><code>array($parent_style)</code> - this is the array of stylesheets that we need\n to run before our stylesheet runs we cant put actual paths that is\n why we name them with a <code>$handle</code>, in this case we need the parent stylesheet to run first (its a dependency)</p></li>\n<li><p><code>wp_get_theme()->get('Version')</code> - this is the number version that\nwill be at the end of the stylesheet <code>URL</code> like this <code>/style.css?ver=1.0</code>, this is for cache purposes, the standard is that you update the version so the latest file is loaded and not a cached version, you dont want to change that number in all the files where you use it right? so use <code>wp_get_theme()->get('Version')</code> it will get the version that is in your <code>style.css</code> file (not the parent one).</p></li>\n</ul>\n\n<p><br/>\nso if you want the resumed version it will be like this:</p>\n\n<pre><code><?php\n\nfunction my_theme_enqueue_styles() {\n //load the parent stylesheet\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n //load the child stylesheet but after the parent stylesheet\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ));\n\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
]
| I've always used @import for the css in my child-theme which i'm now told is bad practice.
What is the best way to set up a child theme going forward? The latest solution on the wordpress codex seems really complex / highly confusing?
There must be a way to do a relatively simple enqueue in my child-theme's functions.php surely?
Any help would be awesome. I feel completely lost / useless trying to find any succinct info on this.
Emily | The code that is in [codex](https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme) for queuing the style of the parent theme instead of using `@import`, is not well commented, so i will comment it more, so you have this:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');
wp_enqueue_style('child-style',
get_stylesheet_directory_uri() . '/style.css',
array($parent_style),
wp_get_theme()->get('Version')
);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');
?>
```
1.- line:
```
$parent_style = 'parent-style';
```
this is literally a string name that you are giving to the theme stylesheet, it will be the `$handle` of the stylesheet you are queuing, it can be what you want, by example `'divi-style'`, in the `HTML` it will be used as the `ID` like this `<link rel="stylesheet" id="divi-style" ...`
2.- line:
```
wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');
```
its registering the stylesheet and queuing it, when its registering it, it will use the name of the first parameter in this case it will be `'parent-style'`, also its using `get_template_directory_uri()` to get the path to the `parent theme` stylesheet.
3.- line:
```
wp_enqueue_style('child-style',
get_stylesheet_directory_uri() . '/style.css',
array($parent_style),
wp_get_theme()->get('Version')
);
```
this is registering and queuing the child theme stylesheet (the current theme stylesheet), this is the usual procedure for a theme, each parameter its already explained [here](https://developer.wordpress.org/reference/functions/wp_enqueue_style/), for the example:
* `'child-style'` - this is the name of this stylesheet the `$handle`
* `get_stylesheet_directory_uri() . '/style.css'` - this is the path to
the stylesheet file.
* `array($parent_style)` - this is the array of stylesheets that we need
to run before our stylesheet runs we cant put actual paths that is
why we name them with a `$handle`, in this case we need the parent stylesheet to run first (its a dependency)
* `wp_get_theme()->get('Version')` - this is the number version that
will be at the end of the stylesheet `URL` like this `/style.css?ver=1.0`, this is for cache purposes, the standard is that you update the version so the latest file is loaded and not a cached version, you dont want to change that number in all the files where you use it right? so use `wp_get_theme()->get('Version')` it will get the version that is in your `style.css` file (not the parent one).
so if you want the resumed version it will be like this:
```
<?php
function my_theme_enqueue_styles() {
//load the parent stylesheet
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
//load the child stylesheet but after the parent stylesheet
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` |
257,592 | <p>im trying to save different value of radio buttons on same name, it works and was able to make checked appear if the correct value is saved. </p>
<p><a href="https://i.stack.imgur.com/zz0H4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zz0H4.png" alt=""></a>
<br>As you can see on the screenshot ABOVE (which is taken on view-source:), it the correct selected input is CHECKED already however even if it's check you can see on the screenshow BELOW that it doesn't display as checked. <br></p>
<p><a href="https://i.stack.imgur.com/UP1zH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UP1zH.png" alt="enter image description here"></a></p>
<p><br>
It's already checked but not displaying , i dont know</p>
| [
{
"answer_id": 257608,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can Also try it checked=\"checked\" some time issue with checked so just try it.</p>\n\n<pre><code>checked\n</code></pre>\n\n<p>Replace with </p>\n\n<pre><code>checked=\"checked\"\n</code></pre>\n"
},
{
"answer_id": 257609,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>In the WordPress back-end you have to use <code>checked=\"checked\"</code> (stricter XHTML), because the CSS will not be applied otherwise:</p>\n\n<pre><code><input type=\"radio\" name=\"colors\" id=\"blue\" checked=\"checked\">\n</code></pre>\n\n<p>this is the CSS that applies the blue dot:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4PD06.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4PD06.png\" alt=\"enter image description here\"></a></p>\n\n<p>WordPress already provides a function for this <a href=\"https://developer.wordpress.org/reference/functions/checked/\" rel=\"nofollow noreferrer\">checked()</a></p>\n\n<pre><code><input type=\"radio\" name=\"colors\" id=\"blue\" <?php checked( 'red', get_option( 'color' ) ); ?> />\n</code></pre>\n\n<p>so you dont have to do an <code>If</code> and <code>echo</code>.</p>\n"
},
{
"answer_id": 257889,
"author": "Archangel17",
"author_id": 110405,
"author_profile": "https://wordpress.stackexchange.com/users/110405",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks a lot everyone for all your time! I really appreciate it! </p>\n\n<p>I've finally found what's causing it to appear and it's because i forgot to remove the old sets of radio buttons with the same id as that on a different meta box. </p>\n\n<p>I've finally fixed it!\nThank you!</p>\n"
},
{
"answer_id": 315958,
"author": "Amit Yaduwanshi",
"author_id": 151819,
"author_profile": "https://wordpress.stackexchange.com/users/151819",
"pm_score": 0,
"selected": false,
"text": "<p>Check if you have another group of input radio button with the same name be the issue. Just rename other groups of input radio button with different name, should resove the issue.</p>\n\n<p>In your case name='seasons' should not be used for another radio button group.</p>\n\n<p>Thanks,</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
]
| im trying to save different value of radio buttons on same name, it works and was able to make checked appear if the correct value is saved.
[](https://i.stack.imgur.com/zz0H4.png)
As you can see on the screenshot ABOVE (which is taken on view-source:), it the correct selected input is CHECKED already however even if it's check you can see on the screenshow BELOW that it doesn't display as checked.
[](https://i.stack.imgur.com/UP1zH.png)
It's already checked but not displaying , i dont know | In the WordPress back-end you have to use `checked="checked"` (stricter XHTML), because the CSS will not be applied otherwise:
```
<input type="radio" name="colors" id="blue" checked="checked">
```
this is the CSS that applies the blue dot:
[](https://i.stack.imgur.com/4PD06.png)
WordPress already provides a function for this [checked()](https://developer.wordpress.org/reference/functions/checked/)
```
<input type="radio" name="colors" id="blue" <?php checked( 'red', get_option( 'color' ) ); ?> />
```
so you dont have to do an `If` and `echo`. |
257,634 | <p>I am using the following code to print another image that is in my images folder in casa a post has no thumbnail but it is giving me errors on the else statement saying that there is a syntax error:</p>
<pre><code><?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else {
echo '<figure><img src="<?php echo get_bloginfo( 'template_directory' ); ?>/images/stone.jpg" /></figure></a>';
}
?>
</code></pre>
<p>However, if I paste this code:</p>
<pre><code><?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else{
}
?>
</code></pre>
<p>It gives no error but also it does not display the thumbnail</p>
<p>Hope you can help</p>
| [
{
"answer_id": 257638,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 2,
"selected": true,
"text": "<p>Try this inside else condition where no image assigned.</p>\n\n<pre><code> if (has_post_thumbnail()) {\n ?><a href=\"<?php the_post_thumbnail_url(); ?>\">\n <?php the_post_thumbnail();?>\n </a><?php\n} else {\n echo '<figure><a href=\"add_link_here\"><img src=\"'.get_bloginfo(\"stylesheet_directory\").'/images/stone.jpg\" /></figure></a>';\n}\n</code></pre>\n"
},
{
"answer_id": 257639,
"author": "user agent",
"author_id": 99178,
"author_profile": "https://wordpress.stackexchange.com/users/99178",
"pm_score": 0,
"selected": false,
"text": "<p>I found a snippet from codex and it actually works.</p>\n\n<pre><code><?php\n // Must be inside a loop.\n\n if ( has_post_thumbnail() ) {\n the_post_thumbnail();\n }\n else {\n echo '<img src=\"' . get_bloginfo( 'stylesheet_directory' ) \n . '/images/stone.jpg\" />';\n }\n?> \n</code></pre>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
]
| I am using the following code to print another image that is in my images folder in casa a post has no thumbnail but it is giving me errors on the else statement saying that there is a syntax error:
```
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else {
echo '<figure><img src="<?php echo get_bloginfo( 'template_directory' ); ?>/images/stone.jpg" /></figure></a>';
}
?>
```
However, if I paste this code:
```
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else{
}
?>
```
It gives no error but also it does not display the thumbnail
Hope you can help | Try this inside else condition where no image assigned.
```
if (has_post_thumbnail()) {
?><a href="<?php the_post_thumbnail_url(); ?>">
<?php the_post_thumbnail();?>
</a><?php
} else {
echo '<figure><a href="add_link_here"><img src="'.get_bloginfo("stylesheet_directory").'/images/stone.jpg" /></figure></a>';
}
``` |
257,645 | <p>Current structure is <code>/%year%/%monthnum%/%postname%.html</code> </p>
<p>Desired structure is <code>/%postname%/</code></p>
<p>Since we are already positioned with urls like <code>domain.com/2015/04/example-post.html</code>, we want people to be redirected to <code>domain.com/example-post/</code>.</p>
<p>I already tried installing some plugins, like <strong>Simple 301 Redirects</strong>, which looked good since it seems to work with rules as shown in the image below:</p>
<p><a href="https://i.stack.imgur.com/uEWro.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uEWro.png" alt="enter image description here"></a></p>
<p>But it didn't worked to us, we get 404 from old urls :(</p>
<p>Adding 301 rules manually is not an options since we have thousands of posts, doing it with a script would be a easy option but I don't think is optimal to have thousands of 301 rules, would it be?</p>
<p>Any other suggestion?</p>
| [
{
"answer_id": 257647,
"author": "Mc Kernel",
"author_id": 107424,
"author_profile": "https://wordpress.stackexchange.com/users/107424",
"pm_score": 0,
"selected": false,
"text": "<p>This tool did the work for me: <a href=\"https://yoast.com/research/permalink-helper.php\" rel=\"nofollow noreferrer\">https://yoast.com/research/permalink-helper.php</a></p>\n\n<p>there you enter the old and new permalinks structure and it gives a single rule, in mi case:</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([^/]+).html$ https://domain.com/$3\n</code></pre>\n"
},
{
"answer_id": 257648,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>You don't need a plugin to achieve your goal. Use server redirect in the <code>.htaccess</code> file because it will not load the processor to interpret the WordPress PHP code and will not consume time. The redirect will be completed before the WordPress runs.</p>\n\n<pre><code>RewriteRule ^[0-9]+/[0-9]+/(.*)\\.html$ /$1 [R=301,L]\n</code></pre>\n\n<p>Where</p>\n\n<ul>\n<li><code>[0-9]+/</code> is the numeric year and month</li>\n<li><code>(.*)</code> is the part we'll use below (<code>example-post</code> in your case)</li>\n<li><code>/$1</code> is the part we've got from the above</li>\n</ul>\n\n<p>301 redirect is completely perfect for SEO.</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107424/"
]
| Current structure is `/%year%/%monthnum%/%postname%.html`
Desired structure is `/%postname%/`
Since we are already positioned with urls like `domain.com/2015/04/example-post.html`, we want people to be redirected to `domain.com/example-post/`.
I already tried installing some plugins, like **Simple 301 Redirects**, which looked good since it seems to work with rules as shown in the image below:
[](https://i.stack.imgur.com/uEWro.png)
But it didn't worked to us, we get 404 from old urls :(
Adding 301 rules manually is not an options since we have thousands of posts, doing it with a script would be a easy option but I don't think is optimal to have thousands of 301 rules, would it be?
Any other suggestion? | You don't need a plugin to achieve your goal. Use server redirect in the `.htaccess` file because it will not load the processor to interpret the WordPress PHP code and will not consume time. The redirect will be completed before the WordPress runs.
```
RewriteRule ^[0-9]+/[0-9]+/(.*)\.html$ /$1 [R=301,L]
```
Where
* `[0-9]+/` is the numeric year and month
* `(.*)` is the part we'll use below (`example-post` in your case)
* `/$1` is the part we've got from the above
301 redirect is completely perfect for SEO. |
257,662 | <p>I am working on a plugin which we need for education website. I have added 3-4 Page templates within my plugin so that we can call when plugin is activated.</p>
<p>Till WordPress <code>4.7</code>, it was working perfectly; but as I upgraded WordPress to the latest (from <code>4.6.3</code>), page templates don't even show in page attribute section.</p>
<p>Here is the code which was working fine with older versions (before <code>4.7</code>):</p>
<pre><code>add_action( 'wp_loaded', 'add_my_templates' );
function add_my_templates() {
if( is_admin() ){
global $wp_object_cache;
$current_theme = wp_get_theme();
$templates = $current_theme->get_page_templates();
$hash = md5( $current_theme->theme_root . '/'. $current_theme->stylesheet );
$templates = $wp_object_cache->get( 'page_templates-'. $hash, 'themes' );
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
wp_cache_replace( 'page_templates-'. $hash, $templates, 'themes' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
</code></pre>
<p>I am searching for the solution from last 2 days, but no luck!</p>
| [
{
"answer_id": 257666,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Your caching insertion code looks very weird and depending on some specific way core calculates hashes for cache and uses them. You need to rewrite that part of the code (which I assume add virtual page templates) to find a more robust insertion method, or just abandon it totally (why not just have actual page templates?)</p>\n\n<p>In general page template are a theme's thing and plugins should not realy have one and instead provide shortcodes or other ways to let the user have pages with their data.</p>\n"
},
{
"answer_id": 257674,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>The Problem:</h1>\n<p>As <a href=\"https://wordpress.stackexchange.com/a/257666/110572\">Mark suggested already</a>, your template loading by manipulating cache is far from standard practice. With these sort of cache alteration, even if you modify your CODE to work with WordPress <code>4.7+</code>, there is no guarantee that you'll not find similar problems in future updates. So better use any of the solutions mentioned below:</p>\n<h1>Theme Solution:</h1>\n<p>Instead of assigning templates form a plugin, you can have actual <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"noreferrer\">page templates</a> in the active theme. Your active theme is the <strong>recommended</strong> place to have these page templates.</p>\n<h1>Plugin Solution</h1>\n<p>However, if you have to assign these templates with your plugin for some reason, then use the <a href=\"https://developer.wordpress.org/reference/hooks/theme_page_templates/\" rel=\"noreferrer\"><code>theme_page_templates</code></a> hook to do so. It'll work for WordPress <code>4.4+</code>.</p>\n<p>Following is the rewrite of your CODE using <code>theme_page_templates</code> filter hook:</p>\n<pre><code>function get_my_template( $template ) {\n $post = get_post();\n $page_template = get_post_meta( $post->ID, '_wp_page_template', true );\n if( $page_template == 'templates/study_home.php' ){\n return plugin_dir_path(__FILE__) . "templates/study_home.php";\n }\n if( $page_template == 'templates/study_job_home.php' ){\n return plugin_dir_path(__FILE__) . "templates/study_job_home.php";\n }\n if( $page_template == 'templates/exams.php' ){\n return plugin_dir_path(__FILE__) . "templates/exams.php";\n }\n if( $page_template == 'templates/colleges.php' ){\n return plugin_dir_path(__FILE__) . "templates/colleges.php";\n }\n return $template;\n}\n\nfunction filter_admin_page_templates( $templates ) {\n $templates['templates/exams.php'] = __('Exams');\n $templates['templates/colleges.php'] = __('Colleges');\n $templates['templates/study_home.php'] = __('Study Home');\n $templates['templates/study_job_home.php'] = __('Study Job Home');\n return $templates;\n}\n\nfunction add_my_templates() {\n if( is_admin() ) {\n add_filter( 'theme_page_templates', 'filter_admin_page_templates' );\n }\n else {\n add_filter( 'page_template', 'get_my_template', 1 );\n }\n}\n\nadd_action( 'wp_loaded', 'add_my_templates' );\n</code></pre>\n<p>Use the above CODE instead of the CODE you've provided. It'll work for any WordPress version <code>4.4</code> and later. I've tested it for WordPress <code>4.7.2</code> & it works fine.</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105597/"
]
| I am working on a plugin which we need for education website. I have added 3-4 Page templates within my plugin so that we can call when plugin is activated.
Till WordPress `4.7`, it was working perfectly; but as I upgraded WordPress to the latest (from `4.6.3`), page templates don't even show in page attribute section.
Here is the code which was working fine with older versions (before `4.7`):
```
add_action( 'wp_loaded', 'add_my_templates' );
function add_my_templates() {
if( is_admin() ){
global $wp_object_cache;
$current_theme = wp_get_theme();
$templates = $current_theme->get_page_templates();
$hash = md5( $current_theme->theme_root . '/'. $current_theme->stylesheet );
$templates = $wp_object_cache->get( 'page_templates-'. $hash, 'themes' );
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
wp_cache_replace( 'page_templates-'. $hash, $templates, 'themes' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
```
I am searching for the solution from last 2 days, but no luck! | The Problem:
============
As [Mark suggested already](https://wordpress.stackexchange.com/a/257666/110572), your template loading by manipulating cache is far from standard practice. With these sort of cache alteration, even if you modify your CODE to work with WordPress `4.7+`, there is no guarantee that you'll not find similar problems in future updates. So better use any of the solutions mentioned below:
Theme Solution:
===============
Instead of assigning templates form a plugin, you can have actual [page templates](https://developer.wordpress.org/themes/template-files-section/page-templates/) in the active theme. Your active theme is the **recommended** place to have these page templates.
Plugin Solution
===============
However, if you have to assign these templates with your plugin for some reason, then use the [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) hook to do so. It'll work for WordPress `4.4+`.
Following is the rewrite of your CODE using `theme_page_templates` filter hook:
```
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ){
return plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ){
return plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ){
return plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ){
return plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
function filter_admin_page_templates( $templates ) {
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
return $templates;
}
function add_my_templates() {
if( is_admin() ) {
add_filter( 'theme_page_templates', 'filter_admin_page_templates' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
add_action( 'wp_loaded', 'add_my_templates' );
```
Use the above CODE instead of the CODE you've provided. It'll work for any WordPress version `4.4` and later. I've tested it for WordPress `4.7.2` & it works fine. |
257,667 | <p>I've been looking and looking for a solution for my problem but i have been unable to find anything. </p>
<p>I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.</p>
<p>Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?</p>
| [
{
"answer_id": 257672,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 3,
"selected": true,
"text": "<p>There's a <a href=\"https://developer.wordpress.org/reference/hooks/validate_username/\" rel=\"nofollow noreferrer\"><code>validate_username</code></a> filter hook that is used by <a href=\"https://developer.wordpress.org/reference/functions/validate_username/\" rel=\"nofollow noreferrer\"><code>validate_user()</code></a> which is in turn used by <a href=\"https://developer.wordpress.org/reference/functions/register_new_user/\" rel=\"nofollow noreferrer\"><code>register_new_user()</code></a>.</p>\n\n<p>So you can disallow usernames containing <code>admin</code> or other prohibited terms:</p>\n\n<pre><code>add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );\nfunction wpse257667_check_username( $valid, $username ) {\n // This array can grow as large as needed. \n $disallowed = array( 'admin', 'other_disallowed_string' );\n foreach( $disallowed as $string ) {\n // If any disallowed string is in the username,\n // mark $valid as false.\n if ( $valid && false !== strpos( $username, $string ) ) {\n $valid = false;\n }\n }\n return $valid;\n}\n</code></pre>\n\n<p>You can add this code to your theme's <code>functions.php</code> file or (preferably) <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">make it a plugin</a>.</p>\n\n<h2>References</h2>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/validate_username/\" rel=\"nofollow noreferrer\"><code>validate_username</code> filter hook</a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/validate_username/\" rel=\"nofollow noreferrer\"><code>validate_user()</code></a> </li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/register_new_user/\" rel=\"nofollow noreferrer\"><code>register_new_user()</code></a></li>\n<li><a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow noreferrer\">Writing a plugin</a></li>\n</ul>\n"
},
{
"answer_id": 257675,
"author": "danbrellis",
"author_id": 34540,
"author_profile": "https://wordpress.stackexchange.com/users/34540",
"pm_score": 1,
"selected": false,
"text": "<p>@pat-j beat me to it by a minute, but I'll elaborate that you can use a reg ex as well:</p>\n\n<pre><code>add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );\nfunction wpse257667_check_username( $valid, $username ) {\n if($valid){\n $matches = null;\n $returnValue = preg_match('/(admin)/i', $username, $matches);\n return empty($matches) ? true : false;\n }\n}\n</code></pre>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80842/"
]
| I've been looking and looking for a solution for my problem but i have been unable to find anything.
I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.
Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words? | There's a [`validate_username`](https://developer.wordpress.org/reference/hooks/validate_username/) filter hook that is used by [`validate_user()`](https://developer.wordpress.org/reference/functions/validate_username/) which is in turn used by [`register_new_user()`](https://developer.wordpress.org/reference/functions/register_new_user/).
So you can disallow usernames containing `admin` or other prohibited terms:
```
add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
// This array can grow as large as needed.
$disallowed = array( 'admin', 'other_disallowed_string' );
foreach( $disallowed as $string ) {
// If any disallowed string is in the username,
// mark $valid as false.
if ( $valid && false !== strpos( $username, $string ) ) {
$valid = false;
}
}
return $valid;
}
```
You can add this code to your theme's `functions.php` file or (preferably) [make it a plugin](https://codex.wordpress.org/Writing_a_Plugin).
References
----------
* [`validate_username` filter hook](https://developer.wordpress.org/reference/hooks/validate_username/)
* [`validate_user()`](https://developer.wordpress.org/reference/functions/validate_username/)
* [`register_new_user()`](https://developer.wordpress.org/reference/functions/register_new_user/)
* [Writing a plugin](https://codex.wordpress.org/Writing_a_Plugin) |
257,684 | <p>Say you have 4 example domains:
1. dogsrule.com
2. dogsrule.cn
3. dogsrulecatsdrool.co.uk
4. dogsrule.au</p>
<p>Currently, each are their own WordPress sites hosted on the same server. Each are only 2 pages, the homepage which includes a form, and a thank you page.</p>
<p>Since they are such small sites and hosted on the same server, would like to consolidate if possible. One option would be to do wordpress multisite setup which may help? Would that be the best option for this scenario or...</p>
<p>Can we have a single normal WordPress install with custom pages for each site that all 4 domains points to respectively?</p>
| [
{
"answer_id": 257687,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>You can use WordPress Multisite version 4.5 or higher to map domains to sites: <a href=\"https://codex.wordpress.org/WordPress_Multisite_Domain_Mapping\" rel=\"nofollow noreferrer\">WordPress Multisite Domain Mapping</a>. This is supported natively, without requiring a plugin.</p>\n"
},
{
"answer_id": 257692,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<h1>Why not multisite:</h1>\n<ul>\n<li><p>Multisite installations are difficult to maintain compared to single site installations.</p>\n</li>\n<li><p>Many useful plugins don't work properly on multisite installations.</p>\n</li>\n<li><p>There may be SEO concern for such short web sites with basically just one page (thank you page doesn't count) that looks very similar from the names. Multisite won't solve this probable issue.</p>\n</li>\n</ul>\n<blockquote>\n<p>I have assumed they have similar content from your example domain names, however, if the content of the four sites are very very different, then form an SEO point of view, having separate sites with a Multisite installation may be better.</p>\n</blockquote>\n<h1>Why not single site:</h1>\n<ul>\n<li>Managing multiple languages may not be easy in a single site installation if you haven't done that before.</li>\n</ul>\n<p>As @Mark suggested in the comment, if you have different language contents in those sites (again just assumption based on example domain names), merging them into a single site may not be easy. You are encouraged to use plugins such as <a href=\"https://wordpress.org/plugins/polylang/\" rel=\"nofollow noreferrer\">Polylang</a> to manage multiple languages. There are thousands of multilingual sites out there running perfectly fine with WordPress. However, if it turns out to be difficult, then you may consider setting up Multisite or even keeping it as it is.</p>\n<h1>Leave them as they are?</h1>\n<p>If the following conditions are true, then may be it's better to just leave them as they are:</p>\n<ul>\n<li><p>Managing these multiple separate installations are not too difficult for you.</p>\n</li>\n<li><p>You may have plugins that are not well tested in multisite installations.</p>\n</li>\n<li><p>You have multilingual content in different sites and you have no experience with WordPress multilingual setup.</p>\n</li>\n</ul>\n<h1>Steps for single site installation</h1>\n<p>If you decide to go for single site installation, or at least want to test it, you may follow the steps below:</p>\n<ol>\n<li><p>Keep any one site (for example <code>dogsrule.com</code>) as the main site.</p>\n</li>\n<li><p>Then make the other three sites point to the main site's web root directory.</p>\n</li>\n<li><p>The main site's home page remains as is & then you create three more pages for the other three sites (for example: <code>dogsrule.com/cn</code>, <code>dogsrule.com/dogs-rule-cats-drool</code> and <code>dogsrule.com/au</code>).</p>\n</li>\n<li><p>Then you may use server rewrite rules to redirect other three domains to the corresponding pages of the main site.</p>\n</li>\n</ol>\n<p>For example, if your web server is Apache, then in your main site's <code>.htaccess</code> file you may use the following CODE (according to the above pages):</p>\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\n\n# redirect rules for the other three domains\nRewriteCond %{HTTP_HOST} ^dogsrule\\.cn$\nRewriteRule . http://dogsrule.com/cn [R=301,L]\nRewriteCond %{HTTP_HOST} ^dogsrulecatsdrool\\.co\\.uk$\nRewriteRule . http://dogsrule.com/dogs-rule-cats-drool [R=301,L]\nRewriteCond %{HTTP_HOST} ^dogsrule\\.au$\nRewriteRule . http://dogsrule.com/au [R=301,L]\n\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n<p>After this you'll have just one site with four main pages (including the home page) and four thank you pages and your other domains will correctly redirect to the corresponding pages.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> You may remove the other three sites after setting up the above, <strong>but don't delete the domains.</strong> Even though, effectively you'll only have one site after this, however, if you delete those domains, old bookmarks and back links will not work.</p>\n</blockquote>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5465/"
]
| Say you have 4 example domains:
1. dogsrule.com
2. dogsrule.cn
3. dogsrulecatsdrool.co.uk
4. dogsrule.au
Currently, each are their own WordPress sites hosted on the same server. Each are only 2 pages, the homepage which includes a form, and a thank you page.
Since they are such small sites and hosted on the same server, would like to consolidate if possible. One option would be to do wordpress multisite setup which may help? Would that be the best option for this scenario or...
Can we have a single normal WordPress install with custom pages for each site that all 4 domains points to respectively? | Why not multisite:
==================
* Multisite installations are difficult to maintain compared to single site installations.
* Many useful plugins don't work properly on multisite installations.
* There may be SEO concern for such short web sites with basically just one page (thank you page doesn't count) that looks very similar from the names. Multisite won't solve this probable issue.
>
> I have assumed they have similar content from your example domain names, however, if the content of the four sites are very very different, then form an SEO point of view, having separate sites with a Multisite installation may be better.
>
>
>
Why not single site:
====================
* Managing multiple languages may not be easy in a single site installation if you haven't done that before.
As @Mark suggested in the comment, if you have different language contents in those sites (again just assumption based on example domain names), merging them into a single site may not be easy. You are encouraged to use plugins such as [Polylang](https://wordpress.org/plugins/polylang/) to manage multiple languages. There are thousands of multilingual sites out there running perfectly fine with WordPress. However, if it turns out to be difficult, then you may consider setting up Multisite or even keeping it as it is.
Leave them as they are?
=======================
If the following conditions are true, then may be it's better to just leave them as they are:
* Managing these multiple separate installations are not too difficult for you.
* You may have plugins that are not well tested in multisite installations.
* You have multilingual content in different sites and you have no experience with WordPress multilingual setup.
Steps for single site installation
==================================
If you decide to go for single site installation, or at least want to test it, you may follow the steps below:
1. Keep any one site (for example `dogsrule.com`) as the main site.
2. Then make the other three sites point to the main site's web root directory.
3. The main site's home page remains as is & then you create three more pages for the other three sites (for example: `dogsrule.com/cn`, `dogsrule.com/dogs-rule-cats-drool` and `dogsrule.com/au`).
4. Then you may use server rewrite rules to redirect other three domains to the corresponding pages of the main site.
For example, if your web server is Apache, then in your main site's `.htaccess` file you may use the following CODE (according to the above pages):
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# redirect rules for the other three domains
RewriteCond %{HTTP_HOST} ^dogsrule\.cn$
RewriteRule . http://dogsrule.com/cn [R=301,L]
RewriteCond %{HTTP_HOST} ^dogsrulecatsdrool\.co\.uk$
RewriteRule . http://dogsrule.com/dogs-rule-cats-drool [R=301,L]
RewriteCond %{HTTP_HOST} ^dogsrule\.au$
RewriteRule . http://dogsrule.com/au [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
After this you'll have just one site with four main pages (including the home page) and four thank you pages and your other domains will correctly redirect to the corresponding pages.
>
> ***Note:*** You may remove the other three sites after setting up the above, **but don't delete the domains.** Even though, effectively you'll only have one site after this, however, if you delete those domains, old bookmarks and back links will not work.
>
>
> |
257,691 | <p>I have a situation where I have to remove a term from a taxonomy. However, there are items that are linked to that taxonomy. Sometimes, these removals are temporary (ie, we stop shipping to a country, but would like items to stay linked to those countries if ever we start shipping to that country again). </p>
<p>Is there any way to 'disable' a term rather than wp_delete_term? Thanks! </p>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, etc. All excluded terms will not be deleted and item links will remain untouched.</p>\n\n<p>Get all countries except Atlantis, El Dorado and Lemuria:</p>\n\n<pre><code><?php\n$args = array(\n 'post_type' => 'A_POST_TYPE', // change this\n 'tax_query' => array(\n array(\n 'taxonomy' => 'countries',\n 'field' => 'slug',\n 'operator' => 'NOT IN', // operator to test\n 'terms' => array( // countries to exclude\n 'atlantis',\n 'el-dorado',\n 'lemuria'\n ) \n )\n )\n);\n\n$result = new WP_Query($args);\n</code></pre>\n\n<p>See <code>WP_Query()</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">Taxonomy Parameters</a> for more.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Since 4.4 there is <code>term meta</code> where you can, say, make it marked your way. \"Disabled\", \"Hidden\" or so.</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/</a></p>\n\n<p>Anyway you have to rethink your queries better.</p>\n"
},
{
"answer_id": 257735,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 3,
"selected": true,
"text": "<p>Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.</p>\n\n<p>The approach I'm taking is to store a term meta when the term is disabled and then to hook into the <code>get_terms_defaults</code> filter to strip disabled terms that would be returned by WP Core's calls to <code>get_terms()</code>, <code>get_the_terms()</code>, etc.</p>\n\n<p>My plugin encapsulates all of this into a class which serves as a wrapper around <code>register_taxonomy()</code>. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies). </p>\n\n<p>See <code>Custom_Taxonomy::enable_term()</code> and <code>Custom_Taxonmy::disable_term()</code> for the code that adds/deletes the relevant term meta; and see <code>Custom_Taxonomy::strip_disabled_terms()</code> for the code that strips disabled terms.</p>\n\n<p>Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)</p>\n\n<pre><code>/**\n * this class is a wrapper around register_taxonomy(), that adds additional functionality\n * to allow terms in the taxonomy so registered to be \"disabled\".\n *\n * Disabled terms will NOT be returned by the various WP Core functions like get_terms(),\n * get_the_terms(), etc.\n *\n * TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()\n */\nclass\nCustom_Taxonomy\n{\n const DISABLED_TERM_META_KEY = '_shc_disabled' ;\n\n public $name ;\n public $can_disable_terms = false ;\n\n /**\n * construct an instance of Custom_Taxonomy\n *\n * @param $taxonomy string Taxonomy key, must not exceed 32 characters\n * @param $post_types array|string post type or array of post types with which the taxonomy should be associated\n * @param $args array Array or query string of arguments for registering a taxonomy\n *\n * params are the same as WP's register_taxonomy() except that $args may have extra keys:\n *\n * 'can_disable_terms' => true|false\n */\n function\n __construct ($taxonomy, $post_types, $args)\n {\n $this->name = $taxonomy ;\n\n // modify args, if needed\n $default_args = array (\n 'can_disable_terms' => false,\n ) ;\n $args = wp_parse_args ($args, $default_args) ;\n\n $this->can_disable_terms = $args['can_disable_terms'] ;\n unset ($args['can_disable_terms']) ;\n\n if ($this->can_disable_terms) {\n // TODO: is there a better filter to hook into than 'get_terms_defaults'?\n // I've tried 'get_terms_args', but that seems to be called too late\n // in the process of builing the WP_Term_Query used by get_terms(), etc\n // to have the meta_query that is added by $this->strip_disabled_terms()\n add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;\n }\n\n // register the taxonomy\n register_taxonomy ($taxonomy, $post_types, $args) ;\n\n return ;\n }\n\n /**\n * disable a term\n *\n * disabling a term will make it appear as if the term does not exist, without actually deleting it\n *\n * @param $term int|string|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure\n */\n function\n disable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;\n }\n\n /**\n * enable a term\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n enable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;\n }\n\n /**\n * strip disabled terms from e.g., get_terms() and get_the_terms()\n *\n * TODO: make sure that this works correctly given WP Core's object caching\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n strip_disabled_terms ($args, $taxonomies)\n {\n if (!$this->can_disable_terms) {\n return ($args) ;\n }\n\n // I *think* the count('taxonomy') check is necesary because get_terms_args() is\n // applied by the WP Core object_term caching infrastructure by\n // passing all taxonomies for a given post_type, and we only want to\n // add this restriction when we are getting the terms for just the\n // this taxonomy\n if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {\n return ($args) ;\n }\n\n $args['meta_query'] = array (\n array (\n 'key' => self::DISABLED_TERM_META_KEY,\n 'compare' => 'NOT EXISTS',\n )\n ) ;\n\n return ($args) ;\n }\n}\n</code></pre>\n\n<h1>My use case</h1>\n\n<p>I've got 2 custom post types, <code>type_a</code> and <code>type_b</code>. <code>type_b</code> has a custom taxonomy, <code>taxonomy_b</code>, the terms of which are the post_title's of all of the posts of type <code>type_a</code>.</p>\n\n<p>Only those posts of <code>type_a</code> whose <code>post_status</code> is <code>publish</code> should have their corresponding terms in <code>taxonomy_b</code> enabled. I accomplish this by hooking into <code>save_post_type_a</code> to insert the terms (if they don't already exist) and enable/disable them, and hook into <code>delete_post</code> to delete them.</p>\n\n<p>If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.</p>\n\n<h1>Questions I still have</h1>\n\n<p>I'm still working on this plugin and there are a few open issues around it's implementation.</p>\n\n<ol>\n<li><p>is the <code>get_terms_defaults</code> filter that I hook into to add the meta_query to <code>WP_Term_Query</code> the best hook to use? I've tried <code>get_terms_args</code>, but that seems to be called too late in the process of builing the WP_Term_Query used by get_terms(), etc. to correctly process the meta_query that is added by <code>Custom_taxonomy::strip_disabled_terms()</code>.</p></li>\n<li><p>I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to <code>get_terms()</code> caches the terms in the taxonomy, and them the term is enabled in the same execution of <code>wp()</code> will a subsequent call to <code>get_terms()</code> include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.</p></li>\n</ol>\n\n<p>If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in!</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257691",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114041/"
]
| I have a situation where I have to remove a term from a taxonomy. However, there are items that are linked to that taxonomy. Sometimes, these removals are temporary (ie, we stop shipping to a country, but would like items to stay linked to those countries if ever we start shipping to that country again).
Is there any way to 'disable' a term rather than wp\_delete\_term? Thanks! | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,696 | <p>I'm trying to edit the revelar theme for my site, I've set up my child theme, created a style.css file and successfully imported all the features from the parent theme, but no matter what I try I can't seem to make any changes to my design. I've tried everything and the code I use in my child theme's style.css file simply isn't showing up on my site. What am I doing wrong?</p>
<p>Really hope someone can help, any input is much appreciated!</p>
<p>My site is: resourcefulliving.dk</p>
<p>Best</p>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, etc. All excluded terms will not be deleted and item links will remain untouched.</p>\n\n<p>Get all countries except Atlantis, El Dorado and Lemuria:</p>\n\n<pre><code><?php\n$args = array(\n 'post_type' => 'A_POST_TYPE', // change this\n 'tax_query' => array(\n array(\n 'taxonomy' => 'countries',\n 'field' => 'slug',\n 'operator' => 'NOT IN', // operator to test\n 'terms' => array( // countries to exclude\n 'atlantis',\n 'el-dorado',\n 'lemuria'\n ) \n )\n )\n);\n\n$result = new WP_Query($args);\n</code></pre>\n\n<p>See <code>WP_Query()</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">Taxonomy Parameters</a> for more.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Since 4.4 there is <code>term meta</code> where you can, say, make it marked your way. \"Disabled\", \"Hidden\" or so.</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/</a></p>\n\n<p>Anyway you have to rethink your queries better.</p>\n"
},
{
"answer_id": 257735,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 3,
"selected": true,
"text": "<p>Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.</p>\n\n<p>The approach I'm taking is to store a term meta when the term is disabled and then to hook into the <code>get_terms_defaults</code> filter to strip disabled terms that would be returned by WP Core's calls to <code>get_terms()</code>, <code>get_the_terms()</code>, etc.</p>\n\n<p>My plugin encapsulates all of this into a class which serves as a wrapper around <code>register_taxonomy()</code>. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies). </p>\n\n<p>See <code>Custom_Taxonomy::enable_term()</code> and <code>Custom_Taxonmy::disable_term()</code> for the code that adds/deletes the relevant term meta; and see <code>Custom_Taxonomy::strip_disabled_terms()</code> for the code that strips disabled terms.</p>\n\n<p>Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)</p>\n\n<pre><code>/**\n * this class is a wrapper around register_taxonomy(), that adds additional functionality\n * to allow terms in the taxonomy so registered to be \"disabled\".\n *\n * Disabled terms will NOT be returned by the various WP Core functions like get_terms(),\n * get_the_terms(), etc.\n *\n * TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()\n */\nclass\nCustom_Taxonomy\n{\n const DISABLED_TERM_META_KEY = '_shc_disabled' ;\n\n public $name ;\n public $can_disable_terms = false ;\n\n /**\n * construct an instance of Custom_Taxonomy\n *\n * @param $taxonomy string Taxonomy key, must not exceed 32 characters\n * @param $post_types array|string post type or array of post types with which the taxonomy should be associated\n * @param $args array Array or query string of arguments for registering a taxonomy\n *\n * params are the same as WP's register_taxonomy() except that $args may have extra keys:\n *\n * 'can_disable_terms' => true|false\n */\n function\n __construct ($taxonomy, $post_types, $args)\n {\n $this->name = $taxonomy ;\n\n // modify args, if needed\n $default_args = array (\n 'can_disable_terms' => false,\n ) ;\n $args = wp_parse_args ($args, $default_args) ;\n\n $this->can_disable_terms = $args['can_disable_terms'] ;\n unset ($args['can_disable_terms']) ;\n\n if ($this->can_disable_terms) {\n // TODO: is there a better filter to hook into than 'get_terms_defaults'?\n // I've tried 'get_terms_args', but that seems to be called too late\n // in the process of builing the WP_Term_Query used by get_terms(), etc\n // to have the meta_query that is added by $this->strip_disabled_terms()\n add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;\n }\n\n // register the taxonomy\n register_taxonomy ($taxonomy, $post_types, $args) ;\n\n return ;\n }\n\n /**\n * disable a term\n *\n * disabling a term will make it appear as if the term does not exist, without actually deleting it\n *\n * @param $term int|string|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure\n */\n function\n disable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;\n }\n\n /**\n * enable a term\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n enable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;\n }\n\n /**\n * strip disabled terms from e.g., get_terms() and get_the_terms()\n *\n * TODO: make sure that this works correctly given WP Core's object caching\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n strip_disabled_terms ($args, $taxonomies)\n {\n if (!$this->can_disable_terms) {\n return ($args) ;\n }\n\n // I *think* the count('taxonomy') check is necesary because get_terms_args() is\n // applied by the WP Core object_term caching infrastructure by\n // passing all taxonomies for a given post_type, and we only want to\n // add this restriction when we are getting the terms for just the\n // this taxonomy\n if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {\n return ($args) ;\n }\n\n $args['meta_query'] = array (\n array (\n 'key' => self::DISABLED_TERM_META_KEY,\n 'compare' => 'NOT EXISTS',\n )\n ) ;\n\n return ($args) ;\n }\n}\n</code></pre>\n\n<h1>My use case</h1>\n\n<p>I've got 2 custom post types, <code>type_a</code> and <code>type_b</code>. <code>type_b</code> has a custom taxonomy, <code>taxonomy_b</code>, the terms of which are the post_title's of all of the posts of type <code>type_a</code>.</p>\n\n<p>Only those posts of <code>type_a</code> whose <code>post_status</code> is <code>publish</code> should have their corresponding terms in <code>taxonomy_b</code> enabled. I accomplish this by hooking into <code>save_post_type_a</code> to insert the terms (if they don't already exist) and enable/disable them, and hook into <code>delete_post</code> to delete them.</p>\n\n<p>If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.</p>\n\n<h1>Questions I still have</h1>\n\n<p>I'm still working on this plugin and there are a few open issues around it's implementation.</p>\n\n<ol>\n<li><p>is the <code>get_terms_defaults</code> filter that I hook into to add the meta_query to <code>WP_Term_Query</code> the best hook to use? I've tried <code>get_terms_args</code>, but that seems to be called too late in the process of builing the WP_Term_Query used by get_terms(), etc. to correctly process the meta_query that is added by <code>Custom_taxonomy::strip_disabled_terms()</code>.</p></li>\n<li><p>I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to <code>get_terms()</code> caches the terms in the taxonomy, and them the term is enabled in the same execution of <code>wp()</code> will a subsequent call to <code>get_terms()</code> include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.</p></li>\n</ol>\n\n<p>If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in!</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114045/"
]
| I'm trying to edit the revelar theme for my site, I've set up my child theme, created a style.css file and successfully imported all the features from the parent theme, but no matter what I try I can't seem to make any changes to my design. I've tried everything and the code I use in my child theme's style.css file simply isn't showing up on my site. What am I doing wrong?
Really hope someone can help, any input is much appreciated!
My site is: resourcefulliving.dk
Best | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,702 | <p>I want my <code>single.php</code> to display posts in the same category for the previous and next posts underneath the post. The problem is that each of my posts belongs to multiple categories, and they are displayed through one of the other categories (24) versus the one I want them to display from (27). Does that even make sense?</p>
<p>Example Categories:</p>
<p>Characters (parent category) (Subcategory IDs listed below:)</p>
<ul>
<li>24 (This category ID displaying instead.)</li>
<li>27 (This is the category ID that I want to display.)</li>
</ul>
<p>Now, my question is, how do I choose the category I want to be pulled from (27) instead of the one being automatically pulled (24)? Here is my code below (that I've found and been fiddling with), with what I've tried so far.</p>
<pre><code> <?php
if (is_single() && in_category('stories')) {
$post_id = $post->ID;
$cat = get_the_category(); //I've tried changing this to my category (both ID and slug)
$current_cat_id = $cat[0]->cat_ID; //Also tried plugging ID and slug
$args = array(
'category' => $current_cat_id, //Also tried plugging ID and slug
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts($args);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$thisindex = array_search($post_id, $ids);
$previd = $ids[$thisindex - 1];
$nextid = $ids[$thisindex + 1];
if (!empty($nextid)) {
?><div class="double-grid"><a rel="next" href="<?php echo get_permalink($nextid) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($nextid); ?>'"> <div class="gold-button">LAST STORY >></div></div></a></div><?php
}
if (!empty($previd)) {
?><div class="double-grid"><a rel="prev" href="<?php echo get_permalink($previd) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($previd); ?>'"> <div class="gold-button">NEXT STORY >></div></div></a></div><?php
}
}
?>
</code></pre>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, etc. All excluded terms will not be deleted and item links will remain untouched.</p>\n\n<p>Get all countries except Atlantis, El Dorado and Lemuria:</p>\n\n<pre><code><?php\n$args = array(\n 'post_type' => 'A_POST_TYPE', // change this\n 'tax_query' => array(\n array(\n 'taxonomy' => 'countries',\n 'field' => 'slug',\n 'operator' => 'NOT IN', // operator to test\n 'terms' => array( // countries to exclude\n 'atlantis',\n 'el-dorado',\n 'lemuria'\n ) \n )\n )\n);\n\n$result = new WP_Query($args);\n</code></pre>\n\n<p>See <code>WP_Query()</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow noreferrer\">Taxonomy Parameters</a> for more.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Since 4.4 there is <code>term meta</code> where you can, say, make it marked your way. \"Disabled\", \"Hidden\" or so.</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/</a></p>\n\n<p>Anyway you have to rethink your queries better.</p>\n"
},
{
"answer_id": 257735,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 3,
"selected": true,
"text": "<p>Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.</p>\n\n<p>The approach I'm taking is to store a term meta when the term is disabled and then to hook into the <code>get_terms_defaults</code> filter to strip disabled terms that would be returned by WP Core's calls to <code>get_terms()</code>, <code>get_the_terms()</code>, etc.</p>\n\n<p>My plugin encapsulates all of this into a class which serves as a wrapper around <code>register_taxonomy()</code>. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies). </p>\n\n<p>See <code>Custom_Taxonomy::enable_term()</code> and <code>Custom_Taxonmy::disable_term()</code> for the code that adds/deletes the relevant term meta; and see <code>Custom_Taxonomy::strip_disabled_terms()</code> for the code that strips disabled terms.</p>\n\n<p>Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)</p>\n\n<pre><code>/**\n * this class is a wrapper around register_taxonomy(), that adds additional functionality\n * to allow terms in the taxonomy so registered to be \"disabled\".\n *\n * Disabled terms will NOT be returned by the various WP Core functions like get_terms(),\n * get_the_terms(), etc.\n *\n * TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()\n */\nclass\nCustom_Taxonomy\n{\n const DISABLED_TERM_META_KEY = '_shc_disabled' ;\n\n public $name ;\n public $can_disable_terms = false ;\n\n /**\n * construct an instance of Custom_Taxonomy\n *\n * @param $taxonomy string Taxonomy key, must not exceed 32 characters\n * @param $post_types array|string post type or array of post types with which the taxonomy should be associated\n * @param $args array Array or query string of arguments for registering a taxonomy\n *\n * params are the same as WP's register_taxonomy() except that $args may have extra keys:\n *\n * 'can_disable_terms' => true|false\n */\n function\n __construct ($taxonomy, $post_types, $args)\n {\n $this->name = $taxonomy ;\n\n // modify args, if needed\n $default_args = array (\n 'can_disable_terms' => false,\n ) ;\n $args = wp_parse_args ($args, $default_args) ;\n\n $this->can_disable_terms = $args['can_disable_terms'] ;\n unset ($args['can_disable_terms']) ;\n\n if ($this->can_disable_terms) {\n // TODO: is there a better filter to hook into than 'get_terms_defaults'?\n // I've tried 'get_terms_args', but that seems to be called too late\n // in the process of builing the WP_Term_Query used by get_terms(), etc\n // to have the meta_query that is added by $this->strip_disabled_terms()\n add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;\n }\n\n // register the taxonomy\n register_taxonomy ($taxonomy, $post_types, $args) ;\n\n return ;\n }\n\n /**\n * disable a term\n *\n * disabling a term will make it appear as if the term does not exist, without actually deleting it\n *\n * @param $term int|string|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure\n */\n function\n disable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;\n }\n\n /**\n * enable a term\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n enable_term ($term, $taxonomy = '', $field = 'name')\n {\n if (!$this->can_disable_terms) {\n return ;\n }\n\n $taxonomy = $taxonomy ? $taxonomy : $this->name ;\n if (is_string ($term)) {\n $term = get_term_by ($field, $term, $taxonomy) ;\n }\n else {\n $term = get_term ($term, $taxonomy) ;\n }\n\n return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;\n }\n\n /**\n * strip disabled terms from e.g., get_terms() and get_the_terms()\n *\n * TODO: make sure that this works correctly given WP Core's object caching\n *\n * @param $term int|WP_Term the term to disable\n * @param $taxonomy string the taxonomy term is in\n * @return bool True on success, false on failure\n */\n function\n strip_disabled_terms ($args, $taxonomies)\n {\n if (!$this->can_disable_terms) {\n return ($args) ;\n }\n\n // I *think* the count('taxonomy') check is necesary because get_terms_args() is\n // applied by the WP Core object_term caching infrastructure by\n // passing all taxonomies for a given post_type, and we only want to\n // add this restriction when we are getting the terms for just the\n // this taxonomy\n if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {\n return ($args) ;\n }\n\n $args['meta_query'] = array (\n array (\n 'key' => self::DISABLED_TERM_META_KEY,\n 'compare' => 'NOT EXISTS',\n )\n ) ;\n\n return ($args) ;\n }\n}\n</code></pre>\n\n<h1>My use case</h1>\n\n<p>I've got 2 custom post types, <code>type_a</code> and <code>type_b</code>. <code>type_b</code> has a custom taxonomy, <code>taxonomy_b</code>, the terms of which are the post_title's of all of the posts of type <code>type_a</code>.</p>\n\n<p>Only those posts of <code>type_a</code> whose <code>post_status</code> is <code>publish</code> should have their corresponding terms in <code>taxonomy_b</code> enabled. I accomplish this by hooking into <code>save_post_type_a</code> to insert the terms (if they don't already exist) and enable/disable them, and hook into <code>delete_post</code> to delete them.</p>\n\n<p>If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.</p>\n\n<h1>Questions I still have</h1>\n\n<p>I'm still working on this plugin and there are a few open issues around it's implementation.</p>\n\n<ol>\n<li><p>is the <code>get_terms_defaults</code> filter that I hook into to add the meta_query to <code>WP_Term_Query</code> the best hook to use? I've tried <code>get_terms_args</code>, but that seems to be called too late in the process of builing the WP_Term_Query used by get_terms(), etc. to correctly process the meta_query that is added by <code>Custom_taxonomy::strip_disabled_terms()</code>.</p></li>\n<li><p>I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to <code>get_terms()</code> caches the terms in the taxonomy, and them the term is enabled in the same execution of <code>wp()</code> will a subsequent call to <code>get_terms()</code> include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.</p></li>\n</ol>\n\n<p>If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in!</p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114049/"
]
| I want my `single.php` to display posts in the same category for the previous and next posts underneath the post. The problem is that each of my posts belongs to multiple categories, and they are displayed through one of the other categories (24) versus the one I want them to display from (27). Does that even make sense?
Example Categories:
Characters (parent category) (Subcategory IDs listed below:)
* 24 (This category ID displaying instead.)
* 27 (This is the category ID that I want to display.)
Now, my question is, how do I choose the category I want to be pulled from (27) instead of the one being automatically pulled (24)? Here is my code below (that I've found and been fiddling with), with what I've tried so far.
```
<?php
if (is_single() && in_category('stories')) {
$post_id = $post->ID;
$cat = get_the_category(); //I've tried changing this to my category (both ID and slug)
$current_cat_id = $cat[0]->cat_ID; //Also tried plugging ID and slug
$args = array(
'category' => $current_cat_id, //Also tried plugging ID and slug
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts($args);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$thisindex = array_search($post_id, $ids);
$previd = $ids[$thisindex - 1];
$nextid = $ids[$thisindex + 1];
if (!empty($nextid)) {
?><div class="double-grid"><a rel="next" href="<?php echo get_permalink($nextid) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($nextid); ?>'"> <div class="gold-button">LAST STORY >></div></div></a></div><?php
}
if (!empty($previd)) {
?><div class="double-grid"><a rel="prev" href="<?php echo get_permalink($previd) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($previd); ?>'"> <div class="gold-button">NEXT STORY >></div></div></a></div><?php
}
}
?>
``` | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,705 | <p>If you go to the ps4 page you will see that the last post is there</p>
<p><a href="http://gamersaction.com/" rel="nofollow noreferrer">My Site</a></p>
<p>Is it necessary to do something for the post to appear on the homepage or should it appear by default?</p>
| [
{
"answer_id": 257707,
"author": "Ashish Dung Dung",
"author_id": 65102,
"author_profile": "https://wordpress.stackexchange.com/users/65102",
"pm_score": 0,
"selected": false,
"text": "<p>You can set auto purge whenever you publish or update a post. \nHowever its better to purge all cache as you might know whats not working post publishing/updating content.</p>\n"
},
{
"answer_id": 257716,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 1,
"selected": false,
"text": "<p>You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired. </p>\n\n<p>Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin. </p>\n\n<p>You can also disable page caching for the front page :</p>\n\n<pre><code>performance - page cache - Don't cache front page\n</code></pre>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| If you go to the ps4 page you will see that the last post is there
[My Site](http://gamersaction.com/)
Is it necessary to do something for the post to appear on the homepage or should it appear by default? | You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired.
Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin.
You can also disable page caching for the front page :
```
performance - page cache - Don't cache front page
``` |
257,708 | <p>My whole theme uses <code>remove_filter( 'the_content', 'wpautop' );</code> which strips the p tags and lines breaks from the output of the WYSIWYG. I have a custom post type <code>events</code> that I would like to bring back the auto p tags and br tags for, but JUST on that custom post type. Is there a way to make sure that filter doesn't get removed on <code>events</code>.</p>
| [
{
"answer_id": 257707,
"author": "Ashish Dung Dung",
"author_id": 65102,
"author_profile": "https://wordpress.stackexchange.com/users/65102",
"pm_score": 0,
"selected": false,
"text": "<p>You can set auto purge whenever you publish or update a post. \nHowever its better to purge all cache as you might know whats not working post publishing/updating content.</p>\n"
},
{
"answer_id": 257716,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 1,
"selected": false,
"text": "<p>You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired. </p>\n\n<p>Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin. </p>\n\n<p>You can also disable page caching for the front page :</p>\n\n<pre><code>performance - page cache - Don't cache front page\n</code></pre>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93770/"
]
| My whole theme uses `remove_filter( 'the_content', 'wpautop' );` which strips the p tags and lines breaks from the output of the WYSIWYG. I have a custom post type `events` that I would like to bring back the auto p tags and br tags for, but JUST on that custom post type. Is there a way to make sure that filter doesn't get removed on `events`. | You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired.
Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin.
You can also disable page caching for the front page :
```
performance - page cache - Don't cache front page
``` |
257,738 | <p>I am using "ugly" permalinks and they are fine in index.php and single.php. I also have a template called sidebar.php that builds a sidebar when at the article/post level. When clicking categories and tags on the sidebar I am then returned with a 404. The actual format is: </p>
<p><a href="http://localhost/mywebsite/tag/mytag" rel="nofollow noreferrer">http://localhost/mywebsite/tag/mytag</a></p>
<p><a href="http://localhost/mywebsite/category/mycategory" rel="nofollow noreferrer">http://localhost/mywebsite/category/mycategory</a></p>
<p>As opposed to what I am expecting for ugly permalinks (and it shows in index.php and single.php):</p>
<p><a href="http://localhost/mywebsite/?tag=1" rel="nofollow noreferrer">http://localhost/mywebsite/?tag=1</a></p>
<p><a href="http://localhost/mywebsite/?cat=3" rel="nofollow noreferrer">http://localhost/mywebsite/?cat=3</a></p>
<p>My tags are defined like this:</p>
<pre><code>function printTags($tags){
if ($tags!=false) {
$return = '';
foreach ($tags as $i){
$return .= '<li><a href="' . home_url() . "/tag/" . $i->slug . '">' . $i->name . '</a></li>';
}
return $return;
}
}
function getTags($tagData){
$tagArray = [];
if($tagData!=false){
foreach ($tagData as $i){
array_push($tagArray, $i->name);
}
}
return $tagArray;
}
</code></pre>
<p>My HTML/PHP is as follows:</p>
<pre><code>function newSuggestion($itemTitle, $sectionSlug, $section, $image, $url, $tags){
echo "<li class='row class'>
<div class='col item'>
<div class='row img-container'>
<div class='col'>
<a href='{$url}'><img src='{$image}' alt='No Image'/></a>
</div>
</div>
<div class='row anotherclass'>
<div class='categories-container'>
<strong><a href='". home_url() ."/category/". $sectionSlug."'>{$section}</a></strong>
</div>
<div class='tags-container'>
<ul class='tags'>". printTags($tags) ."</ul>
</div>
</div>
<div class='row title-container'>
<h2 class='h3'><a href='{$url}'>{$itemTitle}</a></h2>
</div>
</div>
</li>";
}
</code></pre>
<p>Where am I going wrong?</p>
<p>Thank you</p>
<p><strong>EDIT1:</strong></p>
<p>Here is my getPosts function from sidebar.php:</p>
<pre><code> function getPosts($posts, $numSuggestion){
foreach ( $posts as $post ) {
if ($post->ID!=get_the_ID() && $GLOBALS['currentSuggestion']<$numSuggestion && !in_array($post->ID, $GLOBALS['$alreadySuggested'])){
$imageUrl = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
if ($imageUrl == false){
$imageUrl = getDefaultImage();
}
newSuggestion($post->post_title, get_the_category($post->ID)[0]->slug, get_the_category($post->ID)[0]->name, $imageUrl, get_permalink($post->ID), get_the_tags($post->ID));
$GLOBALS['currentSuggestion']++;
array_push($GLOBALS['$alreadySuggested'], $post->ID);
}
}
}
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>I have attempted this: </p>
<pre><code><div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $cat_ID."'>{$section}</a></strong>
</div>
</code></pre>
<p>But with no success, is that the right direction. Where do I make the modification in order to get the categories URL in the format "home_url/category/?cat=123"?</p>
<p><strong>EDIT3:</strong></p>
<p>Not sure I am going towards the right direction, but I have managed to get the right URL, however it returns a 404 (as opposed to categories at article/home level)</p>
<p>I have modified the getPosts function so that <code>get_the_category</code> is mapped to the cat_ID rather than the slug (I am not sure that is the right approach):</p>
<pre><code> newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
</code></pre>
<p>then my newSuggestion function has:</p>
<pre><code> <div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $sectionSlug."'>{$section}</a></strong>
</div>
</code></pre>
<p>Any idea why I am still hitting a 404, while the same URL is functioning in other parts of the site (e.g. home/index or article)? </p>
<p><strong>EDIT4:</strong></p>
<p>I finally got the categories working with this:</p>
<pre><code><div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
</code></pre>
| [
{
"answer_id": 257910,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>home_url() . \"/tag/\" . $i->slug\n</code></pre>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a> function. It will return the link for the term according with the current configuration:</p>\n\n<pre><code>// Assuming $i is a term object\nget_term_link( $i->term_id )\n</code></pre>\n\n<p>For example, your <code>printTags()</code> function would be:</p>\n\n<pre><code>function printTags($tags){\n //Check to see if tags are provided\n if ($tags!=false) {\n $return = '';\n foreach ($tags as $i){\n $return .= '<li><a href=\"' . get_term_link( $i->term_id ) . '\">' . $i->name . '</a></li>';\n }\n return $return;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257919,
"author": "panza",
"author_id": 29402,
"author_profile": "https://wordpress.stackexchange.com/users/29402",
"pm_score": 1,
"selected": true,
"text": "<p>Following the suggestion for tags, I have gotten categories working.</p>\n\n<p>I have modified the getposts function by mapping the category to the cat_ID, rather than the slug:</p>\n\n<pre><code>newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,\n</code></pre>\n\n<p>Then the NewSuggestion functions works out the categories in this way:</p>\n\n<pre><code><div class='categories-container'>\n <strong><a href='\". get_term_link( $sectionSlug) . \"'>{$section}</a></strong>\n </div>\n</code></pre>\n\n<p>The approach works, any suggestion or recommendation on how to improve it is more than welcome. </p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257738",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29402/"
]
| I am using "ugly" permalinks and they are fine in index.php and single.php. I also have a template called sidebar.php that builds a sidebar when at the article/post level. When clicking categories and tags on the sidebar I am then returned with a 404. The actual format is:
<http://localhost/mywebsite/tag/mytag>
<http://localhost/mywebsite/category/mycategory>
As opposed to what I am expecting for ugly permalinks (and it shows in index.php and single.php):
<http://localhost/mywebsite/?tag=1>
<http://localhost/mywebsite/?cat=3>
My tags are defined like this:
```
function printTags($tags){
if ($tags!=false) {
$return = '';
foreach ($tags as $i){
$return .= '<li><a href="' . home_url() . "/tag/" . $i->slug . '">' . $i->name . '</a></li>';
}
return $return;
}
}
function getTags($tagData){
$tagArray = [];
if($tagData!=false){
foreach ($tagData as $i){
array_push($tagArray, $i->name);
}
}
return $tagArray;
}
```
My HTML/PHP is as follows:
```
function newSuggestion($itemTitle, $sectionSlug, $section, $image, $url, $tags){
echo "<li class='row class'>
<div class='col item'>
<div class='row img-container'>
<div class='col'>
<a href='{$url}'><img src='{$image}' alt='No Image'/></a>
</div>
</div>
<div class='row anotherclass'>
<div class='categories-container'>
<strong><a href='". home_url() ."/category/". $sectionSlug."'>{$section}</a></strong>
</div>
<div class='tags-container'>
<ul class='tags'>". printTags($tags) ."</ul>
</div>
</div>
<div class='row title-container'>
<h2 class='h3'><a href='{$url}'>{$itemTitle}</a></h2>
</div>
</div>
</li>";
}
```
Where am I going wrong?
Thank you
**EDIT1:**
Here is my getPosts function from sidebar.php:
```
function getPosts($posts, $numSuggestion){
foreach ( $posts as $post ) {
if ($post->ID!=get_the_ID() && $GLOBALS['currentSuggestion']<$numSuggestion && !in_array($post->ID, $GLOBALS['$alreadySuggested'])){
$imageUrl = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
if ($imageUrl == false){
$imageUrl = getDefaultImage();
}
newSuggestion($post->post_title, get_the_category($post->ID)[0]->slug, get_the_category($post->ID)[0]->name, $imageUrl, get_permalink($post->ID), get_the_tags($post->ID));
$GLOBALS['currentSuggestion']++;
array_push($GLOBALS['$alreadySuggested'], $post->ID);
}
}
}
```
**EDIT2:**
I have attempted this:
```
<div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $cat_ID."'>{$section}</a></strong>
</div>
```
But with no success, is that the right direction. Where do I make the modification in order to get the categories URL in the format "home\_url/category/?cat=123"?
**EDIT3:**
Not sure I am going towards the right direction, but I have managed to get the right URL, however it returns a 404 (as opposed to categories at article/home level)
I have modified the getPosts function so that `get_the_category` is mapped to the cat\_ID rather than the slug (I am not sure that is the right approach):
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
then my newSuggestion function has:
```
<div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $sectionSlug."'>{$section}</a></strong>
</div>
```
Any idea why I am still hitting a 404, while the same URL is functioning in other parts of the site (e.g. home/index or article)?
**EDIT4:**
I finally got the categories working with this:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
``` | Following the suggestion for tags, I have gotten categories working.
I have modified the getposts function by mapping the category to the cat\_ID, rather than the slug:
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
Then the NewSuggestion functions works out the categories in this way:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
```
The approach works, any suggestion or recommendation on how to improve it is more than welcome. |
257,739 | <p>i'm facing a problem with my custom query and need your help.</p>
<p>I want to display all posts of a specific category and I find this snippet:</p>
<pre><code>// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= 0;
// Make a header for the cateogry
// create a custom wordpress query
query_posts("cat=$cat_id&posts_per_page=22");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post();
</code></pre>
<p>This is working fine BUT if a posts is in more then one category then all other posts are displayed 2 and 3 times.</p>
<p>For Example:
I want to list all Post of Category 0
There are 2 Posts - post 1 and post 2; post 1 is also in the category 1
Post 1 and Post 2 will be displayed twice in the frontend.</p>
<p>How can i fix this issue?</p>
<p>Thank you guys.</p>
| [
{
"answer_id": 257910,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>home_url() . \"/tag/\" . $i->slug\n</code></pre>\n\n<p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\"><code>get_term_link()</code></a> function. It will return the link for the term according with the current configuration:</p>\n\n<pre><code>// Assuming $i is a term object\nget_term_link( $i->term_id )\n</code></pre>\n\n<p>For example, your <code>printTags()</code> function would be:</p>\n\n<pre><code>function printTags($tags){\n //Check to see if tags are provided\n if ($tags!=false) {\n $return = '';\n foreach ($tags as $i){\n $return .= '<li><a href=\"' . get_term_link( $i->term_id ) . '\">' . $i->name . '</a></li>';\n }\n return $return;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 257919,
"author": "panza",
"author_id": 29402,
"author_profile": "https://wordpress.stackexchange.com/users/29402",
"pm_score": 1,
"selected": true,
"text": "<p>Following the suggestion for tags, I have gotten categories working.</p>\n\n<p>I have modified the getposts function by mapping the category to the cat_ID, rather than the slug:</p>\n\n<pre><code>newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,\n</code></pre>\n\n<p>Then the NewSuggestion functions works out the categories in this way:</p>\n\n<pre><code><div class='categories-container'>\n <strong><a href='\". get_term_link( $sectionSlug) . \"'>{$section}</a></strong>\n </div>\n</code></pre>\n\n<p>The approach works, any suggestion or recommendation on how to improve it is more than welcome. </p>\n"
}
]
| 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114076/"
]
| i'm facing a problem with my custom query and need your help.
I want to display all posts of a specific category and I find this snippet:
```
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= 0;
// Make a header for the cateogry
// create a custom wordpress query
query_posts("cat=$cat_id&posts_per_page=22");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post();
```
This is working fine BUT if a posts is in more then one category then all other posts are displayed 2 and 3 times.
For Example:
I want to list all Post of Category 0
There are 2 Posts - post 1 and post 2; post 1 is also in the category 1
Post 1 and Post 2 will be displayed twice in the frontend.
How can i fix this issue?
Thank you guys. | Following the suggestion for tags, I have gotten categories working.
I have modified the getposts function by mapping the category to the cat\_ID, rather than the slug:
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
Then the NewSuggestion functions works out the categories in this way:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
```
The approach works, any suggestion or recommendation on how to improve it is more than welcome. |
257,749 | <p>We have a site currently with 1000s of pages with 10s of 1000s of urls linking internally to other pages. All current links use the "ugly" form of their url - ....com/?p=IDNUMBER.</p>
<p>In an SEO initiative, we're recreating the url structure. So, my question is, is it ok to leave the internal links "ugly?"</p>
<p>In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link?</p>
| [
{
"answer_id": 257756,
"author": "passionsplay",
"author_id": 82414,
"author_profile": "https://wordpress.stackexchange.com/users/82414",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the permalink structure is definitely a big deal for an existing site. In order to test the various ways in which changing the permalink structure could break the site, I definitely recommend setting up a test environment.</p>\n\n<blockquote>\n <p>So, my question is, is it ok to leave the internal links \"ugly?\"</p>\n</blockquote>\n\n<p>I'm not sure from an SEO perspective if leaving the urls ugly would matter. It would be tedious, but if you have <code>ssh</code> access, you can use <a href=\"http://wp-cli.org/\" rel=\"nofollow noreferrer\">wp-cli</a> to search and replace the urls in the database:</p>\n\n<pre><code>wp search-replace 'example.com?p=123' 'example.com/post-slug'\n</code></pre>\n\n<p>You could also create a bash script to do that for each url.</p>\n\n<blockquote>\n <p>In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link?</p>\n</blockquote>\n\n<p>The links will not be broken. From a technical standpoint, WordPress performs a <a href=\"https://en.wikipedia.org/wiki/HTTP_302\" rel=\"nofollow noreferrer\"><code>302</code> redirect</a>.</p>\n\n<p>So yes, the site will still 'work', but you indicate that this is in conjunction with an SEO initiative.</p>\n\n<p>SEO things have more to do with the various indexes that search engines (Google, Bing, etc) have of your site. Note that a <code>302</code> redirect implies that the link has \"Moved Temporarily\". Since you want to move all of the existing SEO \"juice\" from the old url to the new url, you need to tell the search engines that \"This content exists, and has <em>permanently</em> moved\". For this you want to use a <a href=\"https://en.wikipedia.org/wiki/HTTP_301\" rel=\"nofollow noreferrer\"><code>301</code> redirect</a>.</p>\n\n<p>There are a couple of ways to do this.</p>\n\n<h2>WordPress Plugins</h2>\n\n<p>There are a few redirection plugins out there that I like:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/safe-redirect-manager/\" rel=\"nofollow noreferrer\">Safe Redirection\nManager</a> </li>\n<li><a href=\"https://wordpress.org/plugins/simple-301-redirects/\" rel=\"nofollow noreferrer\">Simple 301\nRedirects</a></li>\n</ul>\n\n<p>But feel free to search and explore. The main drawback is that you have so many urls to input, and doing so for each url will probably be tedious.</p>\n\n<h2>Redirects at the Server Level</h2>\n\n<p>You can also create <code>301</code> redirects at the server level.</p>\n\n<p>If you are running apache, then you can use its <a href=\"https://httpd.apache.org/docs/2.4/rewrite/remapping.html\" rel=\"nofollow noreferrer\">mod_rewrite</a> engine inside of an <code>.htaccess</code> file.</p>\n\n<p>Nginx has it's own <a href=\"http://nginx.org/en/docs/http/ngx_http_rewrite_module.html\" rel=\"nofollow noreferrer\">rewrite module</a>. I think that this <a href=\"https://www.nginx.com/blog/creating-nginx-rewrite-rules/\" rel=\"nofollow noreferrer\">blog post</a> is a little easier to digest than the docs.</p>\n\n<h2>Getting a List of the URLs</h2>\n\n<p>In any case, one of the challenges is usually getting a complete list of posts, their ids, and the associated slug. </p>\n\n<p>Since the current permalink structure includes the post ID, and the new permalink structure contains the post slug, getting a list of 'before and after' is pretty easy using <code>wp-cli</code>. I've used this before to generate the post list:</p>\n\n<pre><code>wp post list --fields=ID,post_name --format=csv > posts.csv\n</code></pre>\n\n<p>This will give us a file called <code>posts.csv</code> filled with the post id and slug of all the posts:</p>\n\n<pre><code>488,a-new-post-slug\n495,another-new-post-slug\n504,so-many-post-slugs\n# ...\n</code></pre>\n\n<p>From there you can do batch transforms using Vim, Sed, or even a spreadsheet program since it's a csv.</p>\n\n<p>Hope this helps with your planing and execution!</p>\n"
},
{
"answer_id": 257758,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>The simple answer is \"yes\". Wordpress has a \"canonical url\" for each possible page and it will redirect to it if it was accesses from any other url. If you about page ID is \"1\" and the slug is \"about\", <code>example.com/?p=1</code> will generate a request that wordpress will identify as being a request for the about page, but it will not serve the page for it but redirect to <code>example.com/about</code> first.</p>\n\n<p>What is the canonical URL itself changes based on the permalink structure.</p>\n\n<p>This said, I would still allocate some time to change the URLS in the content at some point, even for just an esthetic improvement, but also because relying on some internal \"magic\" number to identify content is just generally not a great idea and if for some reason you will need to restructure the DB (export with the wordpress exporter) the links will at best lead to nowhere.</p>\n"
}
]
| 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37934/"
]
| We have a site currently with 1000s of pages with 10s of 1000s of urls linking internally to other pages. All current links use the "ugly" form of their url - ....com/?p=IDNUMBER.
In an SEO initiative, we're recreating the url structure. So, my question is, is it ok to leave the internal links "ugly?"
In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link? | Changing the permalink structure is definitely a big deal for an existing site. In order to test the various ways in which changing the permalink structure could break the site, I definitely recommend setting up a test environment.
>
> So, my question is, is it ok to leave the internal links "ugly?"
>
>
>
I'm not sure from an SEO perspective if leaving the urls ugly would matter. It would be tedious, but if you have `ssh` access, you can use [wp-cli](http://wp-cli.org/) to search and replace the urls in the database:
```
wp search-replace 'example.com?p=123' 'example.com/post-slug'
```
You could also create a bash script to do that for each url.
>
> In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link?
>
>
>
The links will not be broken. From a technical standpoint, WordPress performs a [`302` redirect](https://en.wikipedia.org/wiki/HTTP_302).
So yes, the site will still 'work', but you indicate that this is in conjunction with an SEO initiative.
SEO things have more to do with the various indexes that search engines (Google, Bing, etc) have of your site. Note that a `302` redirect implies that the link has "Moved Temporarily". Since you want to move all of the existing SEO "juice" from the old url to the new url, you need to tell the search engines that "This content exists, and has *permanently* moved". For this you want to use a [`301` redirect](https://en.wikipedia.org/wiki/HTTP_301).
There are a couple of ways to do this.
WordPress Plugins
-----------------
There are a few redirection plugins out there that I like:
* [Safe Redirection
Manager](https://wordpress.org/plugins/safe-redirect-manager/)
* [Simple 301
Redirects](https://wordpress.org/plugins/simple-301-redirects/)
But feel free to search and explore. The main drawback is that you have so many urls to input, and doing so for each url will probably be tedious.
Redirects at the Server Level
-----------------------------
You can also create `301` redirects at the server level.
If you are running apache, then you can use its [mod\_rewrite](https://httpd.apache.org/docs/2.4/rewrite/remapping.html) engine inside of an `.htaccess` file.
Nginx has it's own [rewrite module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). I think that this [blog post](https://www.nginx.com/blog/creating-nginx-rewrite-rules/) is a little easier to digest than the docs.
Getting a List of the URLs
--------------------------
In any case, one of the challenges is usually getting a complete list of posts, their ids, and the associated slug.
Since the current permalink structure includes the post ID, and the new permalink structure contains the post slug, getting a list of 'before and after' is pretty easy using `wp-cli`. I've used this before to generate the post list:
```
wp post list --fields=ID,post_name --format=csv > posts.csv
```
This will give us a file called `posts.csv` filled with the post id and slug of all the posts:
```
488,a-new-post-slug
495,another-new-post-slug
504,so-many-post-slugs
# ...
```
From there you can do batch transforms using Vim, Sed, or even a spreadsheet program since it's a csv.
Hope this helps with your planing and execution! |
257,757 | <p>I'm creating an advertising portal for a small network using a custom post type. In order to prevent WordPress database corruption or unauthorized access to user information, I need to keep data separated from the advertising app by duplicating custom post type data to an external database when creating and updating an ad post. I'm using the <code>save_post</code> hook to handle when the function should run, and <code>wp_insert_post()</code> to push all post data into the database. What I want to happen is that the post will save in the WordPress database by default, and also save to an external database using my plugin function.</p>
<p>The issue I can't figure out is how to tell <code>wp_insert_post()</code> to use the external database instead of the <code>global $wpdb</code> variable it uses by default, as outlined in WP code reference.</p>
<p>How can I use a custom database with <code>wp_insert_post</code>? Or is there a better method?</p>
<p>My function, based on WordPress codex and Stack Exchange examples:</p>
<pre><code>// Function to push data on update
function my_data_push ($post_id) {
// Check for custom post type
if (get_post_type($post_id) == 'ads'):
// Set up database connection to external ads storage database
$push_to_db = new wpdb('username','password','database','host');
// Insert post data in external database
wp_insert_post($post_id, $wp_error = true);
endif;
}
// Add function to post save hook
add_action('save_post', 'my_data_push');
</code></pre>
| [
{
"answer_id": 257763,
"author": "TMA",
"author_id": 91044,
"author_profile": "https://wordpress.stackexchange.com/users/91044",
"pm_score": -1,
"selected": false,
"text": "<p>For this you need to modify the core wordpress file, in which the function code is written. </p>\n\n<p>You can get the location of the Wordpress functions from the codex\n,too. </p>\n"
},
{
"answer_id": 345210,
"author": "Robin Olsen",
"author_id": 170000,
"author_profile": "https://wordpress.stackexchange.com/users/170000",
"pm_score": 0,
"selected": false,
"text": "<p>I have been searching for an answer to this question for over a month now - i do not think wordpress is very good for any site that has a secure external DB or for anyone who does not want to store customer data in the main wordpress database, which is strange as that seems like a highly valued function.</p>\n\n<p>At any rate i came across this code during my research that may help you - it is a global variable for a external DB... according to the author it is usable in the same way as $wpdb global variable is used.</p>\n\n<p>If you want the author's full blurb on it go here <a href=\"https://bavotasan.com/2011/access-another-database-in-wordpress/\" rel=\"nofollow noreferrer\">https://bavotasan.com/2011/access-another-database-in-wordpress/</a></p>\n\n<p>The code is:\n$newdb = new wpdb($DB_USER, $DB_PASSWORD, $DB_NAME, $DB_HOST);\n$newdb->show_errors();</p>\n\n<p>Hopefully it is of some use to you...</p>\n"
}
]
| 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114085/"
]
| I'm creating an advertising portal for a small network using a custom post type. In order to prevent WordPress database corruption or unauthorized access to user information, I need to keep data separated from the advertising app by duplicating custom post type data to an external database when creating and updating an ad post. I'm using the `save_post` hook to handle when the function should run, and `wp_insert_post()` to push all post data into the database. What I want to happen is that the post will save in the WordPress database by default, and also save to an external database using my plugin function.
The issue I can't figure out is how to tell `wp_insert_post()` to use the external database instead of the `global $wpdb` variable it uses by default, as outlined in WP code reference.
How can I use a custom database with `wp_insert_post`? Or is there a better method?
My function, based on WordPress codex and Stack Exchange examples:
```
// Function to push data on update
function my_data_push ($post_id) {
// Check for custom post type
if (get_post_type($post_id) == 'ads'):
// Set up database connection to external ads storage database
$push_to_db = new wpdb('username','password','database','host');
// Insert post data in external database
wp_insert_post($post_id, $wp_error = true);
endif;
}
// Add function to post save hook
add_action('save_post', 'my_data_push');
``` | I have been searching for an answer to this question for over a month now - i do not think wordpress is very good for any site that has a secure external DB or for anyone who does not want to store customer data in the main wordpress database, which is strange as that seems like a highly valued function.
At any rate i came across this code during my research that may help you - it is a global variable for a external DB... according to the author it is usable in the same way as $wpdb global variable is used.
If you want the author's full blurb on it go here <https://bavotasan.com/2011/access-another-database-in-wordpress/>
The code is:
$newdb = new wpdb($DB\_USER, $DB\_PASSWORD, $DB\_NAME, $DB\_HOST);
$newdb->show\_errors();
Hopefully it is of some use to you... |
257,804 | <p>I'm creating for the first time a theme <strong>from scratch</strong>.</p>
<blockquote>
<p>It's not a child theme</p>
</blockquote>
<p>In theme's <code>function.php</code> file I'm doing</p>
<pre><code>add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'style', get_stylesheet_uri());
});
</code></pre>
<p>But the <code>style.css</code> file is not included in the served html.</p>
<p>Is there something I must do to 'force' inclusion of my theme's CSSes ?</p>
<p>In the <code>index.php</code> I tried to print <code>get_stylesheet_uri()</code> and I got the full URL of my css: <code>http://my.domain.it/wp-content/themes/real/style.css</code></p>
<p>For reference, this is my theme's <code>index.php</code></p>
<pre><code><!-- Inizio di INDEX.PHP -->
<?php
get_header();
?>
<!-- Index.php, dopo get_header(); !-->
<DIV id="container">
<div id="row1">
Riga 1
</div>
<div id="row2">
Riga 2
</div>
</DIV> <?php // id="main_container" ?>
<!-- Index.php, prima di get_footer(); !-->
<?php
get_footer();
?>
<!-- Fine di INDEX.PHP -->
</code></pre>
<p>I'm calling <code>get_header()</code> and my header file is included</p>
<p>This is Header.php </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>
<?php bloginfo( 'name' ); ?>
</title>
<meta name="description" content=" <?php bloginfo( 'description' ); ?> ">
</head>
<body>
<!-- Fine di HEADER.PHP -->
</code></pre>
| [
{
"answer_id": 257805,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": -1,
"selected": false,
"text": "<p>let's try this way:</p>\n\n<pre><code><?php\n//\n// Recommended way to include parent theme styles.\n// (Please see http://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme)\n// \n\nadd_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );\n\nfunction theme_enqueue_styles() {\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array('parent-style')\n );\n}\n</code></pre>\n"
},
{
"answer_id": 257808,
"author": "realtebo",
"author_id": 94289,
"author_profile": "https://wordpress.stackexchange.com/users/94289",
"pm_score": 4,
"selected": true,
"text": "<p>Found: </p>\n\n<p>As stated here: <a href=\"https://codex.wordpress.org/Function_Reference/wp_head\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/wp_head</a>.</p>\n\n<blockquote>\n <p>Put this template tag immediately before tag in a theme template (ex. header.php, index.php).</p>\n</blockquote>\n\n<p>So I added</p>\n\n<pre><code><?php wp_head() ?>\n</code></pre>\n\n<p>just before <code></HEAD</code> and now it works.</p>\n"
},
{
"answer_id": 257826,
"author": "Poorya",
"author_id": 111043,
"author_profile": "https://wordpress.stackexchange.com/users/111043",
"pm_score": -1,
"selected": false,
"text": "<p>use <code><?php wp_head() ?></code> before <code></head></code> in header.php and then use this codes in function.php :</p>\n\n<pre><code>function my_style() {\n wp_enqueue_style( 'style', get_stylesheet_uri()); \n}\n\nadd_action( 'wp_enqueue_scripts', 'my_style' );\n</code></pre>\n"
}
]
| 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94289/"
]
| I'm creating for the first time a theme **from scratch**.
>
> It's not a child theme
>
>
>
In theme's `function.php` file I'm doing
```
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'style', get_stylesheet_uri());
});
```
But the `style.css` file is not included in the served html.
Is there something I must do to 'force' inclusion of my theme's CSSes ?
In the `index.php` I tried to print `get_stylesheet_uri()` and I got the full URL of my css: `http://my.domain.it/wp-content/themes/real/style.css`
For reference, this is my theme's `index.php`
```
<!-- Inizio di INDEX.PHP -->
<?php
get_header();
?>
<!-- Index.php, dopo get_header(); !-->
<DIV id="container">
<div id="row1">
Riga 1
</div>
<div id="row2">
Riga 2
</div>
</DIV> <?php // id="main_container" ?>
<!-- Index.php, prima di get_footer(); !-->
<?php
get_footer();
?>
<!-- Fine di INDEX.PHP -->
```
I'm calling `get_header()` and my header file is included
This is Header.php
```
<!DOCTYPE html>
<html>
<head>
<title>
<?php bloginfo( 'name' ); ?>
</title>
<meta name="description" content=" <?php bloginfo( 'description' ); ?> ">
</head>
<body>
<!-- Fine di HEADER.PHP -->
``` | Found:
As stated here: <https://codex.wordpress.org/Function_Reference/wp_head>.
>
> Put this template tag immediately before tag in a theme template (ex. header.php, index.php).
>
>
>
So I added
```
<?php wp_head() ?>
```
just before `</HEAD` and now it works. |
257,841 | <p>The idea here is the following (I've now uploaded a picture to make it clearer what I need): </p>
<ol>
<li>Create a new page that contains a nicely formatted CSS table.</li>
<li>Each row would refer to a specific post from a specific category.</li>
<li>Each column would refer to specific information about that post (linked title, post date, post author, etc.)</li>
</ol>
<p>Do I have to learn how to fetch that specific information from the database in order to populate this table?
Or is there any easier way to "tell" WordPress what I need to be (dynamically) allocated to each cell?</p>
<p>Thanks! I'm really in the dark as to how to start this. Would appreciate any help I can get.</p>
<p><a href="https://i.stack.imgur.com/Nz8Jx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nz8Jx.jpg" alt="basic image example of what I need"></a></p>
| [
{
"answer_id": 257849,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 2,
"selected": true,
"text": "<p>1: You can use <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=\"nofollow noreferrer\"><code>Page template</code></a> and custom <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> to show posts from a specific category into a page. </p>\n\n<p>2: you can also achive same thing with <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\"><code>shortcode</code></a> where you will have to create a <code>shortcode</code> containing posts from specific category and paste that shortcode into your page.</p>\n\n<p><strong>Update</strong></p>\n\n<p>added sample code for custom page template and wp_query</p>\n\n<pre><code><?php\n/**\n *\n * Template Name: Custom post page\n *\n **/\nget_header(); ?>\n\n<div class=\"main-content\" id=\"main\">\n\n<?php\n$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 10,\n 'category_name' => 'your-category-slug', // replace it with your category slug\n);\n$query = new WP_Query( $args );\nif ( $query->have_posts() ) : ?>\n<table class=\"table post-table\">\n <thead>\n <tr>\n <td><strong>Title</strong></td>\n <td><strong>Author</strong></td>\n <td><strong>Post Date</strong></td>\n </tr>\n </thead>\n<?php while( $query->have_posts() ) : $query->the_post();\n?>\n\n <tbody>\n <tr>\n <td><?php the_title(); ?></td>\n <td><?php the_author(); ?></td>\n <td><?php the_date( 'F j Y'); ?></td>\n </tr>\n </tbody>\n\n<?php endwhile; ?>\n</table>\n<?php endif; wp_reset_postdata(); ?>\n</div>\n<?php get_footer(); ?>\n</code></pre>\n\n<p>create a new php file inside your theme folder and place the above code into it. and them create a new page from WP dashboard and on the right sidebar select your Custom post page template.</p>\n"
},
{
"answer_id": 257850,
"author": "Parzi",
"author_id": 112804,
"author_profile": "https://wordpress.stackexchange.com/users/112804",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php \nif ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n //\n // Post Content here\n //\n } // end while\n} // end if\n?>\n</code></pre>\n\n<p>inside of the while loop you will put in your html for your table and inside of the table you will need to call the_category(); the_title(); the_author(); get_the_date('j/n/y');</p>\n\n<p>NOTE: Make sure your header row to your table is not inside the while loop otherwise you will spit out the header row as well.</p>\n"
},
{
"answer_id": 257855,
"author": "Morshed Maruf",
"author_id": 114147,
"author_profile": "https://wordpress.stackexchange.com/users/114147",
"pm_score": 1,
"selected": false,
"text": "<pre><code><table>\n <tr>\n <th>Category Name</th>\n <th>Post Title</th>\n <th>Author</th>\n <th>Published Date</th>\n </tr>\n\n<?php $temp = $wp_query; $wp_query= null;\n $wp_query = new WP_Query(); $wp_query->query('showposts=10' . '&paged='.$paged);?>\n\n <?php if ( $wp_query->have_posts() ) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>\n <tr>\n <td><?php the_category( ', ', $parents, $post_id ); ?></td>\n <td><a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a></td>\n <td><a href=\"<?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?>\"> <?php the_author(); ?> </a></td>\n <td><?php the_date(); ?></td>\n </tr>\n<?php endwhile; else : ?>\n<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>\n<?php endif; ?>\n</table>\n</code></pre>\n\n<p>You Can try this. Hope this will help you.</p>\n"
}
]
| 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114130/"
]
| The idea here is the following (I've now uploaded a picture to make it clearer what I need):
1. Create a new page that contains a nicely formatted CSS table.
2. Each row would refer to a specific post from a specific category.
3. Each column would refer to specific information about that post (linked title, post date, post author, etc.)
Do I have to learn how to fetch that specific information from the database in order to populate this table?
Or is there any easier way to "tell" WordPress what I need to be (dynamically) allocated to each cell?
Thanks! I'm really in the dark as to how to start this. Would appreciate any help I can get.
[](https://i.stack.imgur.com/Nz8Jx.jpg) | 1: You can use [`Page template`](https://developer.wordpress.org/themes/template-files-section/page-templates/) and custom [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) to show posts from a specific category into a page.
2: you can also achive same thing with [`shortcode`](https://codex.wordpress.org/Shortcode_API) where you will have to create a `shortcode` containing posts from specific category and paste that shortcode into your page.
**Update**
added sample code for custom page template and wp\_query
```
<?php
/**
*
* Template Name: Custom post page
*
**/
get_header(); ?>
<div class="main-content" id="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'category_name' => 'your-category-slug', // replace it with your category slug
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
<table class="table post-table">
<thead>
<tr>
<td><strong>Title</strong></td>
<td><strong>Author</strong></td>
<td><strong>Post Date</strong></td>
</tr>
</thead>
<?php while( $query->have_posts() ) : $query->the_post();
?>
<tbody>
<tr>
<td><?php the_title(); ?></td>
<td><?php the_author(); ?></td>
<td><?php the_date( 'F j Y'); ?></td>
</tr>
</tbody>
<?php endwhile; ?>
</table>
<?php endif; wp_reset_postdata(); ?>
</div>
<?php get_footer(); ?>
```
create a new php file inside your theme folder and place the above code into it. and them create a new page from WP dashboard and on the right sidebar select your Custom post page template. |
257,854 | <p>I see that in other sites that use wordpress this does not happen, so I would like to know how to space without creating a blank paragraph or a &nbsp ?</p>
<p>As you can see in the image, in each space a blank paragraph is created</p>
<p><a href="https://i.stack.imgur.com/RZXjV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZXjV.png" alt="enter image description here"></a></p>
<p>And in the_excerpt too</p>
<p><a href="https://i.stack.imgur.com/r6008.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r6008.png" alt="enter image description here"></a></p>
<p><a href="http://gamersaction.com/" rel="nofollow noreferrer">My site</a> if you want to see more examples</p>
<p>Edit:</p>
<p>The answers of <a href="https://wordpress.stackexchange.com/questions/189692/wordpress-tinymce-prints-empty-p-tag-and-break-html-format/190036#190036">Wordpress tinymce prints empty P tag and break html format</a> did not resolve mine </p>
<p>The paragraphs remain blank and &nbsp keeps appearing</p>
| [
{
"answer_id": 257861,
"author": "Morshed Maruf",
"author_id": 114147,
"author_profile": "https://wordpress.stackexchange.com/users/114147",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\nfunction add_necessary_functions() {\n\n function read_more($limit){\n $post_content = explode(\" \", get_the_content());\n $less_content = array_slice($post_content, $limit);\n echo implode(\" \", $less_content);\n }\n}\nadd_action(\"after_setup_theme\",\"add_necessary_functions\");\n?>\n</code></pre>\n\n<p>You Can create your won read more function with this.\nAnd use $limit as the counter that how many word you want to display.</p>\n"
},
{
"answer_id": 257876,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<p>Judging from your site's content and the comments, you may try using the following CODE in your theme's <code>functions.php</code> file. It'll remove empty <code><p>&nbsp;</p></code> tags from post content:</p>\n<pre><code>add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nadd_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nfunction wpse_257854_remove_empty_p( $content ) {\n return str_ireplace( '<p>&nbsp;</p>', '', $content );\n}\n</code></pre>\n<p>However, after it removes the empty <code><p>&nbsp;</p></code> tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:</p>\n<pre><code>.conteudo-noticia p {\n padding-bottom: 15px;\n}\n</code></pre>\n<p>If <code>nbsp;</code> within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> After making the above changes, please make sure you <strong>clear browser cache</strong> properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.</p>\n</blockquote>\n<h1>Update:</h1>\n<p>If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:</p>\n<pre><code>add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nadd_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nfunction wpse_257854_remove_empty_p( $content ) {\n return str_ireplace( '<p>&nbsp;</p>', '<br>', $content );\n}\n</code></pre>\n<p>This CODE, instead of removing the empty <code>p</code> tags, replaces them with line breaks <code><br></code>. So this way you can control paragraph gaps from within the editor without having empty <code>p</code> tags with <code>&nbsp;</code>.</p>\n"
}
]
| 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| I see that in other sites that use wordpress this does not happen, so I would like to know how to space without creating a blank paragraph or a   ?
As you can see in the image, in each space a blank paragraph is created
[](https://i.stack.imgur.com/RZXjV.png)
And in the\_excerpt too
[](https://i.stack.imgur.com/r6008.png)
[My site](http://gamersaction.com/) if you want to see more examples
Edit:
The answers of [Wordpress tinymce prints empty P tag and break html format](https://wordpress.stackexchange.com/questions/189692/wordpress-tinymce-prints-empty-p-tag-and-break-html-format/190036#190036) did not resolve mine
The paragraphs remain blank and   keeps appearing | Judging from your site's content and the comments, you may try using the following CODE in your theme's `functions.php` file. It'll remove empty `<p> </p>` tags from post content:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '', $content );
}
```
However, after it removes the empty `<p> </p>` tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:
```
.conteudo-noticia p {
padding-bottom: 15px;
}
```
If `nbsp;` within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.
>
> ***Note:*** After making the above changes, please make sure you **clear browser cache** properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.
>
>
>
Update:
=======
If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '<br>', $content );
}
```
This CODE, instead of removing the empty `p` tags, replaces them with line breaks `<br>`. So this way you can control paragraph gaps from within the editor without having empty `p` tags with ` `. |
257,880 | <p>I've created a new widget based on one of my parent theme's custom widgets. In the parent theme the widget files are in the <code>/inc</code> and <code>template-parts</code> folders. I created these same folders in my child theme but can't get the widget to show up on the widgets page. However, it works if I add the widget code to the <code>functions.php</code> file.</p>
<p><strong>UPDATE:</strong></p>
<p>Now I have another problem: <code>Fatal error: Call to undefined function add_action()</code></p>
<p>This is the code I'm using to register the widget:</p>
<pre><code>// Register the widget
function myplugin_register_widgets() {
register_widget( 'Home_Categories' );
}
add_action( 'widgets_init', 'myplugin_register_widgets' );
</code></pre>
<p>This is how the original widget is registered:</p>
<pre><code>// Register the widget
add_action( 'widgets_init', create_function( '', 'return register_widget("Codilight_Widget_Block1");'));
</code></pre>
| [
{
"answer_id": 257861,
"author": "Morshed Maruf",
"author_id": 114147,
"author_profile": "https://wordpress.stackexchange.com/users/114147",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\nfunction add_necessary_functions() {\n\n function read_more($limit){\n $post_content = explode(\" \", get_the_content());\n $less_content = array_slice($post_content, $limit);\n echo implode(\" \", $less_content);\n }\n}\nadd_action(\"after_setup_theme\",\"add_necessary_functions\");\n?>\n</code></pre>\n\n<p>You Can create your won read more function with this.\nAnd use $limit as the counter that how many word you want to display.</p>\n"
},
{
"answer_id": 257876,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<p>Judging from your site's content and the comments, you may try using the following CODE in your theme's <code>functions.php</code> file. It'll remove empty <code><p>&nbsp;</p></code> tags from post content:</p>\n<pre><code>add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nadd_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nfunction wpse_257854_remove_empty_p( $content ) {\n return str_ireplace( '<p>&nbsp;</p>', '', $content );\n}\n</code></pre>\n<p>However, after it removes the empty <code><p>&nbsp;</p></code> tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:</p>\n<pre><code>.conteudo-noticia p {\n padding-bottom: 15px;\n}\n</code></pre>\n<p>If <code>nbsp;</code> within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> After making the above changes, please make sure you <strong>clear browser cache</strong> properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.</p>\n</blockquote>\n<h1>Update:</h1>\n<p>If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:</p>\n<pre><code>add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nadd_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );\nfunction wpse_257854_remove_empty_p( $content ) {\n return str_ireplace( '<p>&nbsp;</p>', '<br>', $content );\n}\n</code></pre>\n<p>This CODE, instead of removing the empty <code>p</code> tags, replaces them with line breaks <code><br></code>. So this way you can control paragraph gaps from within the editor without having empty <code>p</code> tags with <code>&nbsp;</code>.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
]
| I've created a new widget based on one of my parent theme's custom widgets. In the parent theme the widget files are in the `/inc` and `template-parts` folders. I created these same folders in my child theme but can't get the widget to show up on the widgets page. However, it works if I add the widget code to the `functions.php` file.
**UPDATE:**
Now I have another problem: `Fatal error: Call to undefined function add_action()`
This is the code I'm using to register the widget:
```
// Register the widget
function myplugin_register_widgets() {
register_widget( 'Home_Categories' );
}
add_action( 'widgets_init', 'myplugin_register_widgets' );
```
This is how the original widget is registered:
```
// Register the widget
add_action( 'widgets_init', create_function( '', 'return register_widget("Codilight_Widget_Block1");'));
``` | Judging from your site's content and the comments, you may try using the following CODE in your theme's `functions.php` file. It'll remove empty `<p> </p>` tags from post content:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '', $content );
}
```
However, after it removes the empty `<p> </p>` tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:
```
.conteudo-noticia p {
padding-bottom: 15px;
}
```
If `nbsp;` within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.
>
> ***Note:*** After making the above changes, please make sure you **clear browser cache** properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.
>
>
>
Update:
=======
If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '<br>', $content );
}
```
This CODE, instead of removing the empty `p` tags, replaces them with line breaks `<br>`. So this way you can control paragraph gaps from within the editor without having empty `p` tags with ` `. |
257,892 | <p>I am trying to get post title by sql. My sql code is </p>
<pre><code>$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);
if ($result){
foreach($result as $post){
?><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo $post->title; ?></a></li><?php
}
}else{
echo "Sorry, No Post Found.";
}
die();
</code></pre>
<p>Now the problem is I am getting title but the_permalink() is not working.</p>
| [
{
"answer_id": 257894,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure why you are using a custom query and not <code>get_posts()</code> or <code>WP_Query</code> as you should.</p>\n\n<p>Anyway, you need to get the post ID …</p>\n\n<pre><code>$query =\"SELECT wp_posts.post_title AS title , \n wp_posts.post_content AS content,\n wp_posts.post_date AS blogdate ,\n wp_posts.ID AS ID\n</code></pre>\n\n<p>And then just pass this ID to <code>get_permalink()</code>:</p>\n\n<pre><code>get_permalink( $post->ID );\n</code></pre>\n\n<p>Similar for the title attribute:</p>\n\n<pre><code>the_title_attribute( [ 'post' => $post->ID ] );\n</code></pre>\n"
},
{
"answer_id": 357452,
"author": "DavidGM",
"author_id": 181810,
"author_profile": "https://wordpress.stackexchange.com/users/181810",
"pm_score": 0,
"selected": false,
"text": "<p>Let's see...</p>\n\n<pre><code>select p.post_title Title, p.post_date TimeStamp, (SELECT MIN(meta_value) FROM wp_postmeta WHERE meta_key='PermaLink' AND post_id = p.ID) AS PermaLink \n from wp_terms\n inner join wp_term_taxonomy on wp_terms.term_id = wp_term_taxonomy.term_id\n inner join wp_term_relationships wpr on wpr.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id\n inner join wp_posts p on p.ID = wpr.object_id \n /* addidtional conditions - update for your needs */\n where taxonomy= 'category' and p.post_type = 'post' and wp_terms.name = 'News' and p.post_status = 'publish' \n order by post_date DESC;\n</code></pre>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101459/"
]
| I am trying to get post title by sql. My sql code is
```
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);
if ($result){
foreach($result as $post){
?><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo $post->title; ?></a></li><?php
}
}else{
echo "Sorry, No Post Found.";
}
die();
```
Now the problem is I am getting title but the\_permalink() is not working. | I am not sure why you are using a custom query and not `get_posts()` or `WP_Query` as you should.
Anyway, you need to get the post ID …
```
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate ,
wp_posts.ID AS ID
```
And then just pass this ID to `get_permalink()`:
```
get_permalink( $post->ID );
```
Similar for the title attribute:
```
the_title_attribute( [ 'post' => $post->ID ] );
``` |
257,899 | <p>I have a page called <code>mypage</code> and a custom query var called <code>mycustomvar</code>, I am trying to rewrite the following url:</p>
<pre><code>http://example.com/index.php?name=mypage&mycustomvar=someword
</code></pre>
<p>to</p>
<pre><code>http://example.com/mypage/someword
</code></pre>
<p>using</p>
<pre><code>add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?name=mypage&mycustomvar=$matches[1]', 'top' );
</code></pre>
<p>But all I get is:</p>
<pre><code>http://example.com/mypage/?mycustomvar=someword
</code></pre>
<p>showing in the url. I have also tried adding both</p>
<pre><code>add_rewrite_tag( '%mycustomvar%', '([^/]+)' );
</code></pre>
<p>as well as making sure that <code>mycustomvar</code> is added to my custom query vars via the <code>query_vars</code> filter</p>
<p>(and I have tried various combos with and without page name, and using <code>page</code> or <code>pagename</code> in place of <code>name</code>, all with no luck)</p>
| [
{
"answer_id": 257970,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 0,
"selected": false,
"text": "<p>UGH I (maybe) just figured it out. I didn't need my variable to have a name, just a location.</p>\n\n<p>So changing my rewrite rule to this worked:</p>\n\n<pre><code>add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?pagename=mypage&$matches[1]', 'top' );\n</code></pre>\n\n<p>NOW my page will properly load the URL:</p>\n\n<pre><code>http://example.com/mypage/someword\n</code></pre>\n\n<p>ALTHOUGH that said, I have no way now other than url placement to read my variable <code>someword</code> and do something with it, but I guess that is good enough unless someone can point me to a better way that will allow me to query that var by its name....</p>\n"
},
{
"answer_id": 257977,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>OK, let's first get some definitive clarification on the proper query vars.</p>\n<p>Refer to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow noreferrer\">Post and Page parameters</a> on the <code>WP_Query</code> codex page.</p>\n<blockquote>\n<p>name (string) - use post slug.</p>\n<p>pagename (string) - use page slug.</p>\n</blockquote>\n<p>We can confirm this with <code>WP_Query</code>:</p>\n<pre><code>$args = array(\n 'name' => 'mypage'\n);\n$mypage = new WP_Query( $args );\n\necho '<pre>';\nprint_r( $mypage );\necho '</pre>';\n</code></pre>\n<p>which will produce:</p>\n<pre><code>SELECT wp_posts.*\nFROM wp_posts\nWHERE 1=1\nAND wp_posts.post_name = 'mypage'\nAND wp_posts.post_type = 'post'\nORDER BY wp_posts.post_date DESC\n</code></pre>\n<p>It's looking for <code>mypage</code> slug in the <code>post</code> post type. If we change this to <code>pagename</code>, it looks in the <code>page</code> post type.</p>\n<p>The reason it <em>kind of</em> works on the main query with <code>name</code> is due to the <a href=\"https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink\" rel=\"nofollow noreferrer\"><code>redirect_guess_404_permalink</code></a> function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.</p>\n<p>One important thing to note with hierarchical post types- if your page is a child of another page, you must set the <code>pagename</code> query var with the <code>parent/child</code> path, as different parents can have children with the same slug.</p>\n<p>As for your question, changing the query var to <code>pagename</code> works with your original code in v4.7.2 and the Twenty Sixteen theme:</p>\n<pre><code>function wpd_mypage_rewrite() {\n add_rewrite_tag(\n '%mycustomvar%',\n '([^/]+)'\n );\n add_rewrite_rule(\n '^mypage/([^/]+)/?',\n 'index.php?pagename=mypage&mycustomvar=$matches[1]',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_mypage_rewrite' );\n</code></pre>\n<p>Note that I used <code>add_rewrite_tag</code> here. You could <em>instead</em> use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow noreferrer\"><code>query_vars</code> filter</a>. The reason <code>add_rewrite_tag</code> works is that it internally adds the query var via the same filter.</p>\n<p>Don't forget to <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">flush rewrite rules</a> after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.</p>\n<p>You can then <code>echo get_query_var( 'mycustomvar' );</code> in the template, and the value is output.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11023/"
]
| I have a page called `mypage` and a custom query var called `mycustomvar`, I am trying to rewrite the following url:
```
http://example.com/index.php?name=mypage&mycustomvar=someword
```
to
```
http://example.com/mypage/someword
```
using
```
add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?name=mypage&mycustomvar=$matches[1]', 'top' );
```
But all I get is:
```
http://example.com/mypage/?mycustomvar=someword
```
showing in the url. I have also tried adding both
```
add_rewrite_tag( '%mycustomvar%', '([^/]+)' );
```
as well as making sure that `mycustomvar` is added to my custom query vars via the `query_vars` filter
(and I have tried various combos with and without page name, and using `page` or `pagename` in place of `name`, all with no luck) | OK, let's first get some definitive clarification on the proper query vars.
Refer to [Post and Page parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) on the `WP_Query` codex page.
>
> name (string) - use post slug.
>
>
> pagename (string) - use page slug.
>
>
>
We can confirm this with `WP_Query`:
```
$args = array(
'name' => 'mypage'
);
$mypage = new WP_Query( $args );
echo '<pre>';
print_r( $mypage );
echo '</pre>';
```
which will produce:
```
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_name = 'mypage'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
```
It's looking for `mypage` slug in the `post` post type. If we change this to `pagename`, it looks in the `page` post type.
The reason it *kind of* works on the main query with `name` is due to the [`redirect_guess_404_permalink`](https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink) function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.
One important thing to note with hierarchical post types- if your page is a child of another page, you must set the `pagename` query var with the `parent/child` path, as different parents can have children with the same slug.
As for your question, changing the query var to `pagename` works with your original code in v4.7.2 and the Twenty Sixteen theme:
```
function wpd_mypage_rewrite() {
add_rewrite_tag(
'%mycustomvar%',
'([^/]+)'
);
add_rewrite_rule(
'^mypage/([^/]+)/?',
'index.php?pagename=mypage&mycustomvar=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_mypage_rewrite' );
```
Note that I used `add_rewrite_tag` here. You could *instead* use the [`query_vars` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars). The reason `add_rewrite_tag` works is that it internally adds the query var via the same filter.
Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.
You can then `echo get_query_var( 'mycustomvar' );` in the template, and the value is output. |
257,907 | <p>I've a script that I run on each page on my WordPress blog, but it has different input each time.</p>
<p>I have for a example a hint button: The hint button needs to be different on each page.</p>
<pre><code>function answerbutton() {
document.getElementById("answer").innerHTML = 'Readers will see this text as a hint';
}
</code></pre>
<p>What I do now is copy the script to a location and change the value. And load the script from a different location. </p>
<p></p>
<p><a href="https://domainname/page2/hint1" rel="nofollow noreferrer">https://domainname/page2/hint1</a></p>
<p>What I'd like to do is have the script grab some sort of text box on the page editor page. I can use a different input on all pages yet it loads the same text.</p>
<p>I had something in mind like this: </p>
<pre><code><textarea =id"textarea">
function answerbutton() {
document.getElementById("answer").innerHTML = 'ID="textarea"';
}
</code></pre>
<p>But I cannot get it to work.. my javascript skill is zero.
Could someone help me to the right way?
Or give me 'hints'?<br>
Is there a WordPress plugin that can do this for example?</p>
<p>This is what I added to the loop? I guess the index.php:</p>
<pre><code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(__('(more...)'));
$hint1_of_this_page = get_post_meta( get_the_ID(), 'hint1', true );
$hint2_of_this_page = get_post_meta( get_the_ID(), 'hint2', true );
$hint3_of_this_page = get_post_meta( get_the_ID(), 'hint3', true );
$hint4_of_this_page = get_post_meta( get_the_ID(), 'hint4', true );
$answerbutton_of_this_page = get_post_meta( get_the_ID(), 'answerbutton', true );
$correctanswervalidate = get_post_meta( get_the_ID(), 'correctanswervalidate', true );
?></p>
<hr> <?php endwhile; else: ?>
</code></pre>
<p>Thhis is what I added to the footer.php:</p>
<pre><code> <script type="text/javascript">
function answerbutton() {
document.getElementById("answer").innerHTML = '<?php echo $answerbutton_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton() {
document.getElementById("hint1").innerHTML = '<?php echo $hint1_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton2() {
document.getElementById("hint2").innerHTML = '<?php echo $hint2_of_this_page; ?>';
}
</script>
</code></pre>
<p>and this is how I use the custom field:
<a href="https://i.stack.imgur.com/sIhHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sIhHP.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 257970,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 0,
"selected": false,
"text": "<p>UGH I (maybe) just figured it out. I didn't need my variable to have a name, just a location.</p>\n\n<p>So changing my rewrite rule to this worked:</p>\n\n<pre><code>add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?pagename=mypage&$matches[1]', 'top' );\n</code></pre>\n\n<p>NOW my page will properly load the URL:</p>\n\n<pre><code>http://example.com/mypage/someword\n</code></pre>\n\n<p>ALTHOUGH that said, I have no way now other than url placement to read my variable <code>someword</code> and do something with it, but I guess that is good enough unless someone can point me to a better way that will allow me to query that var by its name....</p>\n"
},
{
"answer_id": 257977,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>OK, let's first get some definitive clarification on the proper query vars.</p>\n<p>Refer to <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow noreferrer\">Post and Page parameters</a> on the <code>WP_Query</code> codex page.</p>\n<blockquote>\n<p>name (string) - use post slug.</p>\n<p>pagename (string) - use page slug.</p>\n</blockquote>\n<p>We can confirm this with <code>WP_Query</code>:</p>\n<pre><code>$args = array(\n 'name' => 'mypage'\n);\n$mypage = new WP_Query( $args );\n\necho '<pre>';\nprint_r( $mypage );\necho '</pre>';\n</code></pre>\n<p>which will produce:</p>\n<pre><code>SELECT wp_posts.*\nFROM wp_posts\nWHERE 1=1\nAND wp_posts.post_name = 'mypage'\nAND wp_posts.post_type = 'post'\nORDER BY wp_posts.post_date DESC\n</code></pre>\n<p>It's looking for <code>mypage</code> slug in the <code>post</code> post type. If we change this to <code>pagename</code>, it looks in the <code>page</code> post type.</p>\n<p>The reason it <em>kind of</em> works on the main query with <code>name</code> is due to the <a href=\"https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink\" rel=\"nofollow noreferrer\"><code>redirect_guess_404_permalink</code></a> function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.</p>\n<p>One important thing to note with hierarchical post types- if your page is a child of another page, you must set the <code>pagename</code> query var with the <code>parent/child</code> path, as different parents can have children with the same slug.</p>\n<p>As for your question, changing the query var to <code>pagename</code> works with your original code in v4.7.2 and the Twenty Sixteen theme:</p>\n<pre><code>function wpd_mypage_rewrite() {\n add_rewrite_tag(\n '%mycustomvar%',\n '([^/]+)'\n );\n add_rewrite_rule(\n '^mypage/([^/]+)/?',\n 'index.php?pagename=mypage&mycustomvar=$matches[1]',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_mypage_rewrite' );\n</code></pre>\n<p>Note that I used <code>add_rewrite_tag</code> here. You could <em>instead</em> use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow noreferrer\"><code>query_vars</code> filter</a>. The reason <code>add_rewrite_tag</code> works is that it internally adds the query var via the same filter.</p>\n<p>Don't forget to <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\">flush rewrite rules</a> after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.</p>\n<p>You can then <code>echo get_query_var( 'mycustomvar' );</code> in the template, and the value is output.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114176/"
]
| I've a script that I run on each page on my WordPress blog, but it has different input each time.
I have for a example a hint button: The hint button needs to be different on each page.
```
function answerbutton() {
document.getElementById("answer").innerHTML = 'Readers will see this text as a hint';
}
```
What I do now is copy the script to a location and change the value. And load the script from a different location.
<https://domainname/page2/hint1>
What I'd like to do is have the script grab some sort of text box on the page editor page. I can use a different input on all pages yet it loads the same text.
I had something in mind like this:
```
<textarea =id"textarea">
function answerbutton() {
document.getElementById("answer").innerHTML = 'ID="textarea"';
}
```
But I cannot get it to work.. my javascript skill is zero.
Could someone help me to the right way?
Or give me 'hints'?
Is there a WordPress plugin that can do this for example?
This is what I added to the loop? I guess the index.php:
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(__('(more...)'));
$hint1_of_this_page = get_post_meta( get_the_ID(), 'hint1', true );
$hint2_of_this_page = get_post_meta( get_the_ID(), 'hint2', true );
$hint3_of_this_page = get_post_meta( get_the_ID(), 'hint3', true );
$hint4_of_this_page = get_post_meta( get_the_ID(), 'hint4', true );
$answerbutton_of_this_page = get_post_meta( get_the_ID(), 'answerbutton', true );
$correctanswervalidate = get_post_meta( get_the_ID(), 'correctanswervalidate', true );
?></p>
<hr> <?php endwhile; else: ?>
```
Thhis is what I added to the footer.php:
```
<script type="text/javascript">
function answerbutton() {
document.getElementById("answer").innerHTML = '<?php echo $answerbutton_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton() {
document.getElementById("hint1").innerHTML = '<?php echo $hint1_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton2() {
document.getElementById("hint2").innerHTML = '<?php echo $hint2_of_this_page; ?>';
}
</script>
```
and this is how I use the custom field:
[](https://i.stack.imgur.com/sIhHP.png) | OK, let's first get some definitive clarification on the proper query vars.
Refer to [Post and Page parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) on the `WP_Query` codex page.
>
> name (string) - use post slug.
>
>
> pagename (string) - use page slug.
>
>
>
We can confirm this with `WP_Query`:
```
$args = array(
'name' => 'mypage'
);
$mypage = new WP_Query( $args );
echo '<pre>';
print_r( $mypage );
echo '</pre>';
```
which will produce:
```
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_name = 'mypage'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
```
It's looking for `mypage` slug in the `post` post type. If we change this to `pagename`, it looks in the `page` post type.
The reason it *kind of* works on the main query with `name` is due to the [`redirect_guess_404_permalink`](https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink) function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.
One important thing to note with hierarchical post types- if your page is a child of another page, you must set the `pagename` query var with the `parent/child` path, as different parents can have children with the same slug.
As for your question, changing the query var to `pagename` works with your original code in v4.7.2 and the Twenty Sixteen theme:
```
function wpd_mypage_rewrite() {
add_rewrite_tag(
'%mycustomvar%',
'([^/]+)'
);
add_rewrite_rule(
'^mypage/([^/]+)/?',
'index.php?pagename=mypage&mycustomvar=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_mypage_rewrite' );
```
Note that I used `add_rewrite_tag` here. You could *instead* use the [`query_vars` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars). The reason `add_rewrite_tag` works is that it internally adds the query var via the same filter.
Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.
You can then `echo get_query_var( 'mycustomvar' );` in the template, and the value is output. |
257,925 | <p>I found that Woocommerce is disabling autosave, maybe for good reason, but I'd like to have it turned on and see if it presents an issue. This is what I found in the __construct in their post type class, from wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php....</p>
<pre><code>// Disable Auto Save
add_action( 'admin_print_scripts', array( $this, 'disable_autosave' ) );
</code></pre>
<p>Then further down I see this function....</p>
<pre><code>/**
* Disable the auto-save functionality for Orders.
*/
public function disable_autosave() {
global $post;
if ( $post && in_array( get_post_type( $post->ID ), wc_get_order_types( 'order-meta-boxes' ) ) ) {
wp_dequeue_script( 'autosave' );
}
}
</code></pre>
<p>I tried commenting out the wp_dequeue_script call above just to test if that script was enqueued would it work and still does not autosave. But I'd rather not as it is in the core Woocommerce and subject to updates. How can I re-enable without altering the plugin? Or does anyone have any experience as to why I should not?</p>
<p>The way I am testing is by adding this to the save_post hook:</p>
<pre><code>add_action( 'save_post', 'save_product_meta' );
function save_product_meta( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
error_log("DOING AUTOSAVE for " . $post_id);
return $post_id;
}
</code></pre>
<p>In WordPress admin, I get the log entry while letting a normal post sit on screen without saving, but not when a shop_order type post is created.</p>
| [
{
"answer_id": 257949,
"author": "superwinner",
"author_id": 113690,
"author_profile": "https://wordpress.stackexchange.com/users/113690",
"pm_score": 0,
"selected": false,
"text": "<p>I kinda managed to fix it, don't know if it's the proper way, this is in case of sortable fields, using the stop event and checking if the \"Apply\" button is inside the widget: <a href=\"https://jsfiddle.net/6h5t5r6y\" rel=\"nofollow noreferrer\">https://jsfiddle.net/6h5t5r6y</a></p>\n"
},
{
"answer_id": 258071,
"author": "Weston Ruter",
"author_id": 8521,
"author_profile": "https://wordpress.stackexchange.com/users/8521",
"pm_score": 3,
"selected": true,
"text": "<p>The reason for this is that the widget will run its update logic on <code>keydown</code> <em>and</em> also on <code>change</code> for a given <code>input</code> element. See <a href=\"https://github.com/WordPress/wordpress-develop/blob/4.7.2/src/wp-admin/js/customize-widgets.js#L891-L907\" rel=\"nofollow noreferrer\">https://github.com/WordPress/wordpress-develop/blob/4.7.2/src/wp-admin/js/customize-widgets.js#L891-L907</a></p>\n\n<p>There are some tradeoffs made when widgets were added to the customizer to bring these PHP-driven interfaces into a JS-driven context. It wasn't perfect and so this is part of the reason behind the <a href=\"https://github.com/xwp/wp-js-widgets/\" rel=\"nofollow noreferrer\">JS Widgets</a> feature plugin, to modernize how custom widgets are implemented in the customizer.</p>\n\n<p>If you want to really just listen for when a widget actually changes its state, you can listen for the control's underlying <code>setting</code> change instead. The setting will only be updated once after a given <code>keydown</code> and subsequent <code>change</code> event.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83280/"
]
| I found that Woocommerce is disabling autosave, maybe for good reason, but I'd like to have it turned on and see if it presents an issue. This is what I found in the \_\_construct in their post type class, from wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php....
```
// Disable Auto Save
add_action( 'admin_print_scripts', array( $this, 'disable_autosave' ) );
```
Then further down I see this function....
```
/**
* Disable the auto-save functionality for Orders.
*/
public function disable_autosave() {
global $post;
if ( $post && in_array( get_post_type( $post->ID ), wc_get_order_types( 'order-meta-boxes' ) ) ) {
wp_dequeue_script( 'autosave' );
}
}
```
I tried commenting out the wp\_dequeue\_script call above just to test if that script was enqueued would it work and still does not autosave. But I'd rather not as it is in the core Woocommerce and subject to updates. How can I re-enable without altering the plugin? Or does anyone have any experience as to why I should not?
The way I am testing is by adding this to the save\_post hook:
```
add_action( 'save_post', 'save_product_meta' );
function save_product_meta( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
error_log("DOING AUTOSAVE for " . $post_id);
return $post_id;
}
```
In WordPress admin, I get the log entry while letting a normal post sit on screen without saving, but not when a shop\_order type post is created. | The reason for this is that the widget will run its update logic on `keydown` *and* also on `change` for a given `input` element. See <https://github.com/WordPress/wordpress-develop/blob/4.7.2/src/wp-admin/js/customize-widgets.js#L891-L907>
There are some tradeoffs made when widgets were added to the customizer to bring these PHP-driven interfaces into a JS-driven context. It wasn't perfect and so this is part of the reason behind the [JS Widgets](https://github.com/xwp/wp-js-widgets/) feature plugin, to modernize how custom widgets are implemented in the customizer.
If you want to really just listen for when a widget actually changes its state, you can listen for the control's underlying `setting` change instead. The setting will only be updated once after a given `keydown` and subsequent `change` event. |
257,942 | <p>I've Developed Plugin for using all WordPress Themes. Now depending on Themes requirements I need to change some files on some files. But I don't wants to touch my Plugin.
I've used <pre>add_theme_support('jeweltheme-core');</pre>
I've copied Plugins files and Folders the same way on Plugin. I need to Edit "Widget" files. I cann't find any way to resolve this problem.</p>
<p>Example:
We overrides "WooCommerce" Templates using "templates" directory copying on our Theme and renamed it to "woocommerce". I want exact like this solution. </p>
<p>Thanks</p>
| [
{
"answer_id": 258098,
"author": "Doug Belchamber",
"author_id": 39013,
"author_profile": "https://wordpress.stackexchange.com/users/39013",
"pm_score": 2,
"selected": false,
"text": "<p>If you've written the plugin, then I'd suggest you add something like this:</p>\n\n<pre><code> // Define these constants once in your main plugin init file\n define( 'YOUR_PLUGIN_SLUG', 'your-plugin-slug' );\n define( 'YOUR_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );\n define( 'YOUR_PLUGIN_TEMPLATE_DIR', trailingslashit( YOUR_PLUGIN_DIR ) . 'templates' );\n define( 'YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR', trailingslashit( get_stylesheet_directory() . '/' . YOUR_PLUGIN_SLUG );\n\n // Define a function to locate template files\n function your_plugin_name_get_template_part_location( $part ) {\n $part = $part '.php';\n\n // Look in the user's theme first for the file\n if ( file_exists( YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR . $part ) ) {\n $file = YOUR_PLUGIN_THEME_TEMPLATE_OVERRIDE_PATH_DIR . $part;\n } \n // Otherwise use the file from your plugin\n else {\n $file = YOUR_PLUGIN_TEMPLATE_DIR . $part;\n }\n }\n</code></pre>\n\n<p>First, you define some constants (do this once in your main plugin init file), which you might already have.</p>\n\n<p>Then the function allows you to call files (in my example, template files inside /plugins/your-plugin-name/templates).</p>\n\n<p>For example, you could use</p>\n\n<pre><code>get_template_part(your_plugin_name_get_template_part_location('widget'));\n</code></pre>\n\n<p>Your plugin will first look in the user's theme to see if an override is in place.</p>\n\n<p>If this DOESN'T exist, then it will look in your plugin.</p>\n\n<p>Of course, you can modify this to fit your own directory structure and needs.</p>\n"
},
{
"answer_id": 258105,
"author": "Liton Arefin",
"author_id": 85724,
"author_profile": "https://wordpress.stackexchange.com/users/85724",
"pm_score": 2,
"selected": true,
"text": "<p>I've made my solution like this: </p>\n\n<pre>\n\n function jeweltheme_core_get_template_path($template){\n $located = '';\n\n $template_slug = rtrim( $template, '.php' );\n $template = $template_slug . '.php';\n\n $this_plugin_dir = WP_PLUGIN_DIR.'/'.str_replace( basename( __FILE__), \"\", plugin_basename(__FILE__) );\n\n if ( $template ) {\n if ( file_exists(get_stylesheet_directory() . '/jeweltheme-core/' . $template)) {\n $located = get_stylesheet_directory() . '/jeweltheme-core/' . $template;\n } else if ( file_exists(get_template_directory() . '/jeweltheme-core/' . $template) ) {\n $located = get_template_directory() . '/jeweltheme-core/' . $template;\n } else if ( file_exists( $this_plugin_dir . $template) ) {\n $located = $this_plugin_dir . $template;\n }\n }\n\n return $located;\n }\n</pre>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85724/"
]
| I've Developed Plugin for using all WordPress Themes. Now depending on Themes requirements I need to change some files on some files. But I don't wants to touch my Plugin.
I've used
```
add_theme_support('jeweltheme-core');
```
I've copied Plugins files and Folders the same way on Plugin. I need to Edit "Widget" files. I cann't find any way to resolve this problem.
Example:
We overrides "WooCommerce" Templates using "templates" directory copying on our Theme and renamed it to "woocommerce". I want exact like this solution.
Thanks | I've made my solution like this:
```
function jeweltheme_core_get_template_path($template){
$located = '';
$template_slug = rtrim( $template, '.php' );
$template = $template_slug . '.php';
$this_plugin_dir = WP_PLUGIN_DIR.'/'.str_replace( basename( __FILE__), "", plugin_basename(__FILE__) );
if ( $template ) {
if ( file_exists(get_stylesheet_directory() . '/jeweltheme-core/' . $template)) {
$located = get_stylesheet_directory() . '/jeweltheme-core/' . $template;
} else if ( file_exists(get_template_directory() . '/jeweltheme-core/' . $template) ) {
$located = get_template_directory() . '/jeweltheme-core/' . $template;
} else if ( file_exists( $this_plugin_dir . $template) ) {
$located = $this_plugin_dir . $template;
}
}
return $located;
}
``` |
257,955 | <p>I'm using <code>Wordpress Settings API</code>. Everything works as it should except this <code>select</code> dropdown. When I select an option, the value echoed is correct but in the dropdown it displays the default first value i.e <code>6</code> and not the selected one. Where am I going wrong?</p>
<pre><code> public function someplugin_select() {
$options = get_option( 'plugin_252calc');
echo $options; //shows the correct value selected
$items = array();
for ($i=6; $i <=10; $i+= 0.1)
{
$items[] = $i;
}
echo '<select id="cf-nb" name="cf-nb">';
foreach ( $items as $item )
{
echo '<option value="'. $item .'"';
if ( $item == $options ) echo' selected="selected"';
echo '>'. $item .'</option>';
}
echo '</select>';
}
</code></pre>
| [
{
"answer_id": 257959,
"author": "Roel Magdaleno",
"author_id": 99204,
"author_profile": "https://wordpress.stackexchange.com/users/99204",
"pm_score": 0,
"selected": false,
"text": "<p>I went through this, and I could tell that there's a WP function called <code>selected</code>, which you can see in this <a href=\"https://developer.wordpress.org/reference/functions/selected/\" rel=\"nofollow noreferrer\">link</a>. Use this function instead of doing: <code>if ( $item == $options )</code>. And your code could look like this:</p>\n\n<pre><code>foreach ( $seconds as $second => $time ) {\n ?>\n <option value=\"<?php echo $second; ?>\" <?php selected( $browser_cache_ttl, $second ); ?>><?php echo $time; ?></option>\n <?php\n}\n</code></pre>\n\n<p>So that function loops through <code>$seconds</code> and get the <code>$second</code> and <code>$time</code>, put te <code>$second</code> as value, then call the selected function which the first parameter is the value to compare and the second one is the current value, if those values are the same, it'll be selected.</p>\n\n<p>I think that's what you're looking for. Tell me if it worked.</p>\n"
},
{
"answer_id": 257962,
"author": "Vishal Kumar Sahu",
"author_id": 101300,
"author_profile": "https://wordpress.stackexchange.com/users/101300",
"pm_score": 0,
"selected": false,
"text": "<p>Replace your select with this... Hope it works...</p>\n\n<pre><code> echo '<select id=\"cf-nb\" name=\"cf-nb\">';\n foreach ( $items as $item ){\n $if_selected = $item == $options ? \"selected='selected'\" : \"\";\n echo \"<option value='{$item}' {$if_selected}>$item</option>\";\n\n }\n\n echo '</select>'; \n</code></pre>\n"
},
{
"answer_id": 257964,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 3,
"selected": true,
"text": "<p>The reason your <code>$item == $option</code> condition is always failing is because of the way PHP compares floats!</p>\n\n<p>Try the following instead:</p>\n\n<pre><code>echo \"<option value='$item'\" . selected (abs ($item - $options) <= 0.01, true, false) . \">$item</option>\" ;\n</code></pre>\n\n<p>See <a href=\"http://php.net/manual/en/language.types.float.php#language.types.float.comparison\" rel=\"nofollow noreferrer\">Comparing floats</a> for more info.</p>\n"
},
{
"answer_id": 408367,
"author": "710dev_null",
"author_id": 224711,
"author_profile": "https://wordpress.stackexchange.com/users/224711",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have any better answers, but I feel I have a similar-enough issue to add to this question instead of making a new one.</p>\n<p>I started with <a href=\"https://www.youtube.com/watch?v=hbJiwm5YL5Q&t=3969s\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=hbJiwm5YL5Q&t=3969s</a> and got as far as 1:05:00 and this is my current version is</p>\n<pre><code>function selectpageHTML() {?>\n <select name="lp_actPage"> \n <?\n $pages = get_pages(); foreach ( $pages as $page ) { \n $title = $page->post_title;\n echo "<option value='$title'" . selected(get_option('lp_actPage', $title)) .">$title</option>";\n } ?>\n </select>\n <?}\n</code></pre>\n<p>however, instead of comparing floats I was thinking I could compare string values instead, but so far no dice.</p>\n<p>I also tried assigning a variable as the page ID and using that variable as the option value as well as the 2nd argument in the get_option() function, but still no joy.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257955",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/447/"
]
| I'm using `Wordpress Settings API`. Everything works as it should except this `select` dropdown. When I select an option, the value echoed is correct but in the dropdown it displays the default first value i.e `6` and not the selected one. Where am I going wrong?
```
public function someplugin_select() {
$options = get_option( 'plugin_252calc');
echo $options; //shows the correct value selected
$items = array();
for ($i=6; $i <=10; $i+= 0.1)
{
$items[] = $i;
}
echo '<select id="cf-nb" name="cf-nb">';
foreach ( $items as $item )
{
echo '<option value="'. $item .'"';
if ( $item == $options ) echo' selected="selected"';
echo '>'. $item .'</option>';
}
echo '</select>';
}
``` | The reason your `$item == $option` condition is always failing is because of the way PHP compares floats!
Try the following instead:
```
echo "<option value='$item'" . selected (abs ($item - $options) <= 0.01, true, false) . ">$item</option>" ;
```
See [Comparing floats](http://php.net/manual/en/language.types.float.php#language.types.float.comparison) for more info. |
257,957 | <p>When I change the redirect https in my .htaccess the site returns the message "Too many redirects" loop. </p>
<p>This is the modified .htaccess</p>
<pre><code>RewriteCond %{HTTPS} off
RewriteRule (.*)$ https://www.mywebsite.it/$1 [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I also added in the wp-config.php: </p>
<pre><code>define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
</code></pre>
| [
{
"answer_id": 257960,
"author": "Poofy",
"author_id": 114069,
"author_profile": "https://wordpress.stackexchange.com/users/114069",
"pm_score": -1,
"selected": false,
"text": "<p><p>\ndo you want to push all the traffic to https?<p>\ni have ssl installed on my site, and i use this code to force all the incoming traffic to HHTPS : (put it above all of your codes in .htaccess )\n<br><strong>first remove the previous code you added to wp-config.php</strong><br>\n<strong>and remove the previous code in .htaccess</strong> <p></p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.yoursite.it/$1 [R,L]\n</code></pre>\n\n<p>be sure to know your server port. and replace it if it's not 80.<p>\nhere is more info if you need : - i took my code from here :) <p>\ni hope it help you too<p>\n<a href=\"http://www.webhostinghub.com/help/learn/website/ssl/force-website-to-use-ssl\" rel=\"nofollow noreferrer\">use https with .htaccess</a></p>\n"
},
{
"answer_id": 282168,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 0,
"selected": false,
"text": "<p>Since many shared hosts use additional DNS management now such as such as Cloudflare...or similar, do you know if you are using such thing ?</p>\n\n<p>If so you need to make sure cloudflare is set to Full https as well as possibly using a cloudflare plugin to prevent too many redirects or loops. </p>\n"
},
{
"answer_id": 299803,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on.</p>\n"
}
]
| 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54283/"
]
| When I change the redirect https in my .htaccess the site returns the message "Too many redirects" loop.
This is the modified .htaccess
```
RewriteCond %{HTTPS} off
RewriteRule (.*)$ https://www.mywebsite.it/$1 [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I also added in the wp-config.php:
```
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
``` | Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on. |
257,978 | <p>I have created a page template and custom post type 'pa' that I want to display on the page template. I have the template created, also made <code>archive-pa.php</code>, <code>single-pa.php</code><br>
My template: <code>page-pa.php</code> contains this: </p>
<pre><code><?php
/*
Template Name: Personal Assistants
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php $loop = new WP_Query( array( 'post_type' => 'pa', 'posts_per_page' => 6 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
stuff here
<?php endwhile; wp_reset_query(); ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
</code></pre>
<p>This will only show whatever text I put where 'stuff here' is. As I am new to this I have no idea on how I should display the actual posts; I need some more php queries here to display the posts like it would a normal blog? I found the get_ queries, I have no idea how to construct it - all I can work out is a bit of a hack where I use the permalink as a custom link menu item but I do also want to create a custom search, and categories sidebar too. Any help would be much appreciated!</p>
| [
{
"answer_id": 257960,
"author": "Poofy",
"author_id": 114069,
"author_profile": "https://wordpress.stackexchange.com/users/114069",
"pm_score": -1,
"selected": false,
"text": "<p><p>\ndo you want to push all the traffic to https?<p>\ni have ssl installed on my site, and i use this code to force all the incoming traffic to HHTPS : (put it above all of your codes in .htaccess )\n<br><strong>first remove the previous code you added to wp-config.php</strong><br>\n<strong>and remove the previous code in .htaccess</strong> <p></p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.yoursite.it/$1 [R,L]\n</code></pre>\n\n<p>be sure to know your server port. and replace it if it's not 80.<p>\nhere is more info if you need : - i took my code from here :) <p>\ni hope it help you too<p>\n<a href=\"http://www.webhostinghub.com/help/learn/website/ssl/force-website-to-use-ssl\" rel=\"nofollow noreferrer\">use https with .htaccess</a></p>\n"
},
{
"answer_id": 282168,
"author": "Randomer11",
"author_id": 62291,
"author_profile": "https://wordpress.stackexchange.com/users/62291",
"pm_score": 0,
"selected": false,
"text": "<p>Since many shared hosts use additional DNS management now such as such as Cloudflare...or similar, do you know if you are using such thing ?</p>\n\n<p>If so you need to make sure cloudflare is set to Full https as well as possibly using a cloudflare plugin to prevent too many redirects or loops. </p>\n"
},
{
"answer_id": 299803,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on.</p>\n"
}
]
| 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/257978",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114208/"
]
| I have created a page template and custom post type 'pa' that I want to display on the page template. I have the template created, also made `archive-pa.php`, `single-pa.php`
My template: `page-pa.php` contains this:
```
<?php
/*
Template Name: Personal Assistants
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php $loop = new WP_Query( array( 'post_type' => 'pa', 'posts_per_page' => 6 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
stuff here
<?php endwhile; wp_reset_query(); ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
```
This will only show whatever text I put where 'stuff here' is. As I am new to this I have no idea on how I should display the actual posts; I need some more php queries here to display the posts like it would a normal blog? I found the get\_ queries, I have no idea how to construct it - all I can work out is a bit of a hack where I use the permalink as a custom link menu item but I do also want to create a custom search, and categories sidebar too. Any help would be much appreciated! | Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on. |
258,007 | <p>Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.</p>
<p>I figured since all the information is there; there must be a way to do this automatically.</p>
<p><strong>Question:</strong> How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.</p>
<p>Any help is much appreciated!</p>
| [
{
"answer_id": 258009,
"author": "Richard Webster",
"author_id": 101457,
"author_profile": "https://wordpress.stackexchange.com/users/101457",
"pm_score": 4,
"selected": true,
"text": "<p>This is what you need, taken from - <a href=\"https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail\">https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail</a></p>\n\n<pre><code>add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);\n\nfunction change_attachement_image_attributes( $attr, $attachment ){\n // Get post parent\n $parent = get_post_field( 'post_parent', $attachment);\n\n // Get post type to check if it's product\n $type = get_post_field( 'post_type', $parent);\n if( $type != 'product' ){\n return $attr;\n }\n\n /// Get title\n $title = get_post_field( 'post_title', $parent);\n\n $attr['alt'] = $title;\n $attr['title'] = $title;\n\n return $attr;\n}\n</code></pre>\n"
},
{
"answer_id": 279386,
"author": "Luke van Lathum",
"author_id": 6895,
"author_profile": "https://wordpress.stackexchange.com/users/6895",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone searching, I would recommend editing the code above so if a product image already has an alt tag do not override it with the post title. This way you can still add product image titles if necessary.</p>\n\n<pre><code>add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);\nfunction change_attachement_image_attributes( $attr, $attachment ) {\n// Get post parent\n$parent = get_post_field( 'post_parent', $attachment);\n\n// Get post type to check if it's product\n$type = get_post_field( 'post_type', $parent);\nif( $type != 'product' ){\n return $attr;\n}\n\n/// Get title\n$title = get_post_field( 'post_title', $parent);\n\nif( $attr['alt'] == ''){\n $attr['alt'] = $title;\n $attr['title'] = $title;\n}\n\nreturn $attr;\n}\n</code></pre>\n"
},
{
"answer_id": 323773,
"author": "Danail Emandiev",
"author_id": 132252,
"author_profile": "https://wordpress.stackexchange.com/users/132252",
"pm_score": 2,
"selected": false,
"text": "<p>If anyone is looking for a fast and easy way to use product titles as product image alt tags, I recommend the <a href=\"https://wordpress.org/plugins/woo-image-seo/\" rel=\"nofollow noreferrer\">Woo Image SEO plugin</a>.<br>\nThe plugin can also handle the creation of title attributes.<br>\nAdditionally, you can customize the attributes by including the product's category and tag in any order.\n<a href=\"https://i.stack.imgur.com/FWIJQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FWIJQ.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
]
| Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.
I figured since all the information is there; there must be a way to do this automatically.
**Question:** How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.
Any help is much appreciated! | This is what you need, taken from - <https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail>
```
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
``` |
258,013 | <p>I'm trying to echo <strong>all</strong> of my custom taxonomies, but this only prints out the first one:</p>
<pre><code>$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
echo 'skill-' . $term->slug;
</code></pre>
<p>Does anyone have an idea of what I've done wrong?</p>
| [
{
"answer_id": 258009,
"author": "Richard Webster",
"author_id": 101457,
"author_profile": "https://wordpress.stackexchange.com/users/101457",
"pm_score": 4,
"selected": true,
"text": "<p>This is what you need, taken from - <a href=\"https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail\">https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail</a></p>\n\n<pre><code>add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);\n\nfunction change_attachement_image_attributes( $attr, $attachment ){\n // Get post parent\n $parent = get_post_field( 'post_parent', $attachment);\n\n // Get post type to check if it's product\n $type = get_post_field( 'post_type', $parent);\n if( $type != 'product' ){\n return $attr;\n }\n\n /// Get title\n $title = get_post_field( 'post_title', $parent);\n\n $attr['alt'] = $title;\n $attr['title'] = $title;\n\n return $attr;\n}\n</code></pre>\n"
},
{
"answer_id": 279386,
"author": "Luke van Lathum",
"author_id": 6895,
"author_profile": "https://wordpress.stackexchange.com/users/6895",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone searching, I would recommend editing the code above so if a product image already has an alt tag do not override it with the post title. This way you can still add product image titles if necessary.</p>\n\n<pre><code>add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);\nfunction change_attachement_image_attributes( $attr, $attachment ) {\n// Get post parent\n$parent = get_post_field( 'post_parent', $attachment);\n\n// Get post type to check if it's product\n$type = get_post_field( 'post_type', $parent);\nif( $type != 'product' ){\n return $attr;\n}\n\n/// Get title\n$title = get_post_field( 'post_title', $parent);\n\nif( $attr['alt'] == ''){\n $attr['alt'] = $title;\n $attr['title'] = $title;\n}\n\nreturn $attr;\n}\n</code></pre>\n"
},
{
"answer_id": 323773,
"author": "Danail Emandiev",
"author_id": 132252,
"author_profile": "https://wordpress.stackexchange.com/users/132252",
"pm_score": 2,
"selected": false,
"text": "<p>If anyone is looking for a fast and easy way to use product titles as product image alt tags, I recommend the <a href=\"https://wordpress.org/plugins/woo-image-seo/\" rel=\"nofollow noreferrer\">Woo Image SEO plugin</a>.<br>\nThe plugin can also handle the creation of title attributes.<br>\nAdditionally, you can customize the attributes by including the product's category and tag in any order.\n<a href=\"https://i.stack.imgur.com/FWIJQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FWIJQ.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91093/"
]
| I'm trying to echo **all** of my custom taxonomies, but this only prints out the first one:
```
$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
echo 'skill-' . $term->slug;
```
Does anyone have an idea of what I've done wrong? | This is what you need, taken from - <https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail>
```
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
``` |
258,026 | <p>I am trying to build a plugin that will replace one file from the theme. It will be plugin for certain theme that has a file placed in includes folder to the path would be: </p>
<p>wp-content/theme/includes/example-file.php</p>
<p>This example-file.php is loaded in header and footer also via <code>include</code></p>
<p>I want to make a plugin that would overwrite example-file.php so that theme includes that file from my plugin and not the includes folder from theme. </p>
<p>How is that possible, what would be the best way to do this?</p>
| [
{
"answer_id": 258032,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>WordPress way (recommended):</h1>\n\n<p>In your plugin, use the WordPress <code>theme_file_path</code> filter hook to change the file from the plugin. Use the following CODE in your plugin:</p>\n\n<pre><code>add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );\nfunction wpse_258026_modify_theme_include_file( $path, $file = '' ) {\n if( 'includes/example-file.php' === $file ) {\n // change path here as required\n return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';\n }\n return $path;\n}\n</code></pre>\n\n<p>Then you may include the file in your theme using the <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path</code></a> function, like this:</p>\n\n<pre><code>include get_theme_file_path( 'includes/example-file.php' );\n</code></pre>\n\n<p>Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.</p>\n\n<p>Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification. </p>\n\n<h1>Controlling Page Template from Plugin:</h1>\n\n<p>If you are looking for controlling page templates from your plugin, then you may <a href=\"https://wordpress.stackexchange.com/a/257674/110572\">check out this answer</a> to see how to do it.</p>\n\n<h1>PHP way:</h1>\n\n<p>If you are including the <code>wp-content/theme/<your-theme>/includes/example-file.php</code> file using simple <code>include</code> call with <strong>relative path</strong> inside header, footer templates like the following:</p>\n\n<pre><code>include 'includes/example-file.php';\n</code></pre>\n\n<p>then it's also possible to replace it with the plugin's version of <code>includes/example-file.php</code> file using PHP <code>set_include_path()</code> function.</p>\n\n<p>Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path: </p>\n\n<pre><code>set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );\n</code></pre>\n\n<p>After that, for any <code>include</code> with relative path in <code>header.php</code>, <code>footer.php</code> etc. PHP will look for the file in your plugin's directory first.</p>\n\n<blockquote>\n <p>However, this method <strong><em>will not work</em></strong> if you include the file using absolute path in your header, footer etc.</p>\n</blockquote>\n"
},
{
"answer_id": 258114,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one.This works if you are using page templates.</p>\n\n<pre><code>add_filter(\"page_template\", \"plugin_function_name\");\nfunction plugin_function_name($page_template)\n{\n $id = substr($page_template, strrpos($page_template, '/') + 1);\n if ($id == 'includes/example-file.php') {\n $page_template = plugin_dir_path(__FILE__) . 'includes/example-file.php';\n }\n return $page_template;\n}\n</code></pre>\n"
}
]
| 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81451/"
]
| I am trying to build a plugin that will replace one file from the theme. It will be plugin for certain theme that has a file placed in includes folder to the path would be:
wp-content/theme/includes/example-file.php
This example-file.php is loaded in header and footer also via `include`
I want to make a plugin that would overwrite example-file.php so that theme includes that file from my plugin and not the includes folder from theme.
How is that possible, what would be the best way to do this? | WordPress way (recommended):
============================
In your plugin, use the WordPress `theme_file_path` filter hook to change the file from the plugin. Use the following CODE in your plugin:
```
add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );
function wpse_258026_modify_theme_include_file( $path, $file = '' ) {
if( 'includes/example-file.php' === $file ) {
// change path here as required
return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';
}
return $path;
}
```
Then you may include the file in your theme using the [`get_theme_file_path`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) function, like this:
```
include get_theme_file_path( 'includes/example-file.php' );
```
Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.
Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification.
Controlling Page Template from Plugin:
======================================
If you are looking for controlling page templates from your plugin, then you may [check out this answer](https://wordpress.stackexchange.com/a/257674/110572) to see how to do it.
PHP way:
========
If you are including the `wp-content/theme/<your-theme>/includes/example-file.php` file using simple `include` call with **relative path** inside header, footer templates like the following:
```
include 'includes/example-file.php';
```
then it's also possible to replace it with the plugin's version of `includes/example-file.php` file using PHP `set_include_path()` function.
Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path:
```
set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );
```
After that, for any `include` with relative path in `header.php`, `footer.php` etc. PHP will look for the file in your plugin's directory first.
>
> However, this method ***will not work*** if you include the file using absolute path in your header, footer etc.
>
>
> |
258,048 | <p>I am working with twenty fourteen theme.
I want to customize the full-width template for my needs, to make it wider on specific pages.
so I copied it into a sub folder in my child theme.</p>
<p>how do I embed styling that will affect this template ONLY?</p>
<p>tried this, but it doesnt work: <a href="http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen" rel="nofollow noreferrer">http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen</a></p>
<p>p.s: I am not a developer :(</p>
| [
{
"answer_id": 258032,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>WordPress way (recommended):</h1>\n\n<p>In your plugin, use the WordPress <code>theme_file_path</code> filter hook to change the file from the plugin. Use the following CODE in your plugin:</p>\n\n<pre><code>add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );\nfunction wpse_258026_modify_theme_include_file( $path, $file = '' ) {\n if( 'includes/example-file.php' === $file ) {\n // change path here as required\n return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';\n }\n return $path;\n}\n</code></pre>\n\n<p>Then you may include the file in your theme using the <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path</code></a> function, like this:</p>\n\n<pre><code>include get_theme_file_path( 'includes/example-file.php' );\n</code></pre>\n\n<p>Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.</p>\n\n<p>Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification. </p>\n\n<h1>Controlling Page Template from Plugin:</h1>\n\n<p>If you are looking for controlling page templates from your plugin, then you may <a href=\"https://wordpress.stackexchange.com/a/257674/110572\">check out this answer</a> to see how to do it.</p>\n\n<h1>PHP way:</h1>\n\n<p>If you are including the <code>wp-content/theme/<your-theme>/includes/example-file.php</code> file using simple <code>include</code> call with <strong>relative path</strong> inside header, footer templates like the following:</p>\n\n<pre><code>include 'includes/example-file.php';\n</code></pre>\n\n<p>then it's also possible to replace it with the plugin's version of <code>includes/example-file.php</code> file using PHP <code>set_include_path()</code> function.</p>\n\n<p>Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path: </p>\n\n<pre><code>set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );\n</code></pre>\n\n<p>After that, for any <code>include</code> with relative path in <code>header.php</code>, <code>footer.php</code> etc. PHP will look for the file in your plugin's directory first.</p>\n\n<blockquote>\n <p>However, this method <strong><em>will not work</em></strong> if you include the file using absolute path in your header, footer etc.</p>\n</blockquote>\n"
},
{
"answer_id": 258114,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one.This works if you are using page templates.</p>\n\n<pre><code>add_filter(\"page_template\", \"plugin_function_name\");\nfunction plugin_function_name($page_template)\n{\n $id = substr($page_template, strrpos($page_template, '/') + 1);\n if ($id == 'includes/example-file.php') {\n $page_template = plugin_dir_path(__FILE__) . 'includes/example-file.php';\n }\n return $page_template;\n}\n</code></pre>\n"
}
]
| 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258048",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114256/"
]
| I am working with twenty fourteen theme.
I want to customize the full-width template for my needs, to make it wider on specific pages.
so I copied it into a sub folder in my child theme.
how do I embed styling that will affect this template ONLY?
tried this, but it doesnt work: <http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen>
p.s: I am not a developer :( | WordPress way (recommended):
============================
In your plugin, use the WordPress `theme_file_path` filter hook to change the file from the plugin. Use the following CODE in your plugin:
```
add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );
function wpse_258026_modify_theme_include_file( $path, $file = '' ) {
if( 'includes/example-file.php' === $file ) {
// change path here as required
return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';
}
return $path;
}
```
Then you may include the file in your theme using the [`get_theme_file_path`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) function, like this:
```
include get_theme_file_path( 'includes/example-file.php' );
```
Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.
Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification.
Controlling Page Template from Plugin:
======================================
If you are looking for controlling page templates from your plugin, then you may [check out this answer](https://wordpress.stackexchange.com/a/257674/110572) to see how to do it.
PHP way:
========
If you are including the `wp-content/theme/<your-theme>/includes/example-file.php` file using simple `include` call with **relative path** inside header, footer templates like the following:
```
include 'includes/example-file.php';
```
then it's also possible to replace it with the plugin's version of `includes/example-file.php` file using PHP `set_include_path()` function.
Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path:
```
set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );
```
After that, for any `include` with relative path in `header.php`, `footer.php` etc. PHP will look for the file in your plugin's directory first.
>
> However, this method ***will not work*** if you include the file using absolute path in your header, footer etc.
>
>
> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.