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
|
---|---|---|---|---|---|---|
286,423 |
<p>I wanted some information about on how to achieve the below senario. Can anyone help me out please.</p>
<p>Ok so here is what i have got so far.</p>
<p>I have two custom post types. And i am pulling & merging those to load randomly. They load randomly and with post types alternatively.</p>
<p>Ex: post type 1, post type 2, post type 1, post type 2 etc..</p>
<p>I have achieved this so far. Now while loading posts i want them into 3 columns(masonry format). </p>
<pre><code><div class="row">
<div id="grid-content">
<?php
// Fetch quotes
$quotes_query = new WP_Query( array(
'post_type'=> 'quote',
'orderby' => 'rand',
'posts_per_page' => 4,
) );
// Fetch founders
$founders_query = new WP_Query( array(
'post_type'=> 'founder',
'orderby' => 'rand',
'posts_per_page' => 3,
) );
// List of merged founder and quotes
$mergedposts = array();
for ( $i = 0; $i < 10; $i++ ) {
// Add quotes to list
if ( isset( $quotes_query->posts[ $i ] ) ) {
$mergedposts[] = $quotes_query->posts[ $i ];
}
// Add founder to list
if ( isset( $founders_query->posts[ $i ] ) ) {
$mergedposts[] = $founders_query->posts[ $i ];
}
}
foreach( $mergedposts as $post ) :
setup_postdata($post);
?>
<div class="col-md-4 col-sm-6 col-xs-12 foundersnetwork_col">
<div class="foundersnetwork_list">
<?php if ( get_post_type( get_the_ID() ) == 'quote' ) { ?>
<div class="foundersnetwork_content" style="background-color: <?php the_field('background_color'); ?>;">
<h4><?php the_field('quote_data'); ?></h4>
</div>
<?php } ?>
<?php if(get_post_type( get_the_ID() ) == 'founder'){ ?>
<div class="foundersnetwork_img"><?php the_post_thumbnail('full'); ?></div>
<?php } ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</code></pre>
<p>But the 4th post must fall into 1st column, 5th post into 2nd column, 6th post into 3rd column and so on.. </p>
<p>example:</p>
<pre><code><div class="col1">
post 1
post 4
post 7
</div>
<div class="col2">
post 2
post 5
</div>
<div class="col3">
post 3
post 6
</div>
</code></pre>
<p>**** Updated ****</p>
<p>Found a solution. Not exactly how i wanted but this will do the trick as the 4th falls under 1st no matter of the other posts - <a href="https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid" rel="nofollow noreferrer">https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid</a></p>
<p>So this is solved now. Thanks to everyone who spent time on this.</p>
|
[
{
"answer_id": 286424,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>If that <code>col-4</code> class does what your example suggests it does, then just wrapping each post in <code>col-4</code> would achieve the same effect:</p>\n\n<pre><code><div class=\"col-4\">\nPost 1\n</div>\n<div class=\"col-4\">\nPost 2\n</div>\n<div class=\"col-4\">\nPost 3\n</div>\n<div class=\"col-4\">\nPost 4\n</div>\n<div class=\"col-4\">\nPost 5\n</div>\n<div class=\"col-4\">\nPost 6\n</div>\n</code></pre>\n\n<p>Then you don't need to do anything special with WP_Query at all.</p>\n"
},
{
"answer_id": 286427,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>You may use this as follow:- </p>\n\n<pre><code> $query = new WP_Query( array(\n 'post_type' => 'post',\n 'order' => 'DESC',\n 'post_status' => ' publish',\n 'posts_per_page' => 3\n ) );\n\n while ($query->have_posts()): $query->the_post();\n echo\"<div class=\"col-4\">\";\n the_title();\n echo\"</div>\";\n endwhile;\n wp_reset_postdata();\n</code></pre>\n\n<p>You may Please check it and let me know if you succeded in your goal.</p>\n"
}
] |
2017/11/20
|
[
"https://wordpress.stackexchange.com/questions/286423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124296/"
] |
I wanted some information about on how to achieve the below senario. Can anyone help me out please.
Ok so here is what i have got so far.
I have two custom post types. And i am pulling & merging those to load randomly. They load randomly and with post types alternatively.
Ex: post type 1, post type 2, post type 1, post type 2 etc..
I have achieved this so far. Now while loading posts i want them into 3 columns(masonry format).
```
<div class="row">
<div id="grid-content">
<?php
// Fetch quotes
$quotes_query = new WP_Query( array(
'post_type'=> 'quote',
'orderby' => 'rand',
'posts_per_page' => 4,
) );
// Fetch founders
$founders_query = new WP_Query( array(
'post_type'=> 'founder',
'orderby' => 'rand',
'posts_per_page' => 3,
) );
// List of merged founder and quotes
$mergedposts = array();
for ( $i = 0; $i < 10; $i++ ) {
// Add quotes to list
if ( isset( $quotes_query->posts[ $i ] ) ) {
$mergedposts[] = $quotes_query->posts[ $i ];
}
// Add founder to list
if ( isset( $founders_query->posts[ $i ] ) ) {
$mergedposts[] = $founders_query->posts[ $i ];
}
}
foreach( $mergedposts as $post ) :
setup_postdata($post);
?>
<div class="col-md-4 col-sm-6 col-xs-12 foundersnetwork_col">
<div class="foundersnetwork_list">
<?php if ( get_post_type( get_the_ID() ) == 'quote' ) { ?>
<div class="foundersnetwork_content" style="background-color: <?php the_field('background_color'); ?>;">
<h4><?php the_field('quote_data'); ?></h4>
</div>
<?php } ?>
<?php if(get_post_type( get_the_ID() ) == 'founder'){ ?>
<div class="foundersnetwork_img"><?php the_post_thumbnail('full'); ?></div>
<?php } ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
```
But the 4th post must fall into 1st column, 5th post into 2nd column, 6th post into 3rd column and so on..
example:
```
<div class="col1">
post 1
post 4
post 7
</div>
<div class="col2">
post 2
post 5
</div>
<div class="col3">
post 3
post 6
</div>
```
\*\*\*\* Updated \*\*\*\*
Found a solution. Not exactly how i wanted but this will do the trick as the 4th falls under 1st no matter of the other posts - <https://bootsnipp.com/snippets/featured/pinterest-like-responsive-grid>
So this is solved now. Thanks to everyone who spent time on this.
|
If that `col-4` class does what your example suggests it does, then just wrapping each post in `col-4` would achieve the same effect:
```
<div class="col-4">
Post 1
</div>
<div class="col-4">
Post 2
</div>
<div class="col-4">
Post 3
</div>
<div class="col-4">
Post 4
</div>
<div class="col-4">
Post 5
</div>
<div class="col-4">
Post 6
</div>
```
Then you don't need to do anything special with WP\_Query at all.
|
286,440 |
<p>I know how to find the post_excerpt using the post ID, but is it possible to find a post ID using an excerpt? Every time I search for this, all that comes up is how to find the post_excerpt from the ID. Thanks for any help.</p>
|
[
{
"answer_id": 286442,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Via the APIs? No</strong>, the excerpt is not an option in <code>WP_Query</code> which is what powers all the other functions. <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">See here for a full list of options</a></p>\n\n<p>It will attempt this indirectly if you do a search, but this also searches the post content and title</p>\n\n<p><strong>To do this explictly you will need to do a raw SQL query</strong>, via <code>$wpdb</code>, and keep in mind this probably won't be a fast query, I would advise against it</p>\n"
},
{
"answer_id": 286443,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 3,
"selected": true,
"text": "<p>You can get the post ID from the excerpt, but as far as I can tell, <code>WP_Query</code> doesn't support this (very well), so you need to write a custom WPDB query.</p>\n\n<pre><code>function get_post_id_by_excerpt($excerpt) {\n global $wpdb;\n $result = $wpdb->get_row( \n $wpdb->prepare(\"SELECT ID FROM {$wpdb->prefix}posts WHERE post_excerpt LIKE %s\", $excerpt) \n );\n return $result;\n}\n</code></pre>\n\n<p>For this to work, you need to pass the exact excerpt (incl. HTML) to the function</p>\n"
},
{
"answer_id": 286447,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>99% of the time it is not possible, at least not without a ridiculously slow algorithm.</p>\n\n<p>The reason is that excerpt are may both be automatically generated and/or sanitized, making the resulting excerpt to not exactly match neither the <code>post_content</code> nor <code>post_excerpt</code>.</p>\n\n<p>Chances of getting it right when you are dealing with a manual excerpt are probably much higher than when dealing with automatic one, but people add them relatively rarely.</p>\n"
}
] |
2017/11/20
|
[
"https://wordpress.stackexchange.com/questions/286440",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123624/"
] |
I know how to find the post\_excerpt using the post ID, but is it possible to find a post ID using an excerpt? Every time I search for this, all that comes up is how to find the post\_excerpt from the ID. Thanks for any help.
|
You can get the post ID from the excerpt, but as far as I can tell, `WP_Query` doesn't support this (very well), so you need to write a custom WPDB query.
```
function get_post_id_by_excerpt($excerpt) {
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare("SELECT ID FROM {$wpdb->prefix}posts WHERE post_excerpt LIKE %s", $excerpt)
);
return $result;
}
```
For this to work, you need to pass the exact excerpt (incl. HTML) to the function
|
286,464 |
<h1>**EDIT: I finally figured this out. Scroll down for my self-answered self-accepted answer (green check mark) **</h1>
<p>I'm currently using <code>functions.php</code> to redirect <code>https</code> urls to <code>http</code> for a site which currently has no SSL certificate:</p>
<pre><code>function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
function bhww_ssl_template_redirect() {
if ( shapeSpace_check_https() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( preg_replace( '|^https://|', 'http://', $_SERVER['REQUEST_URI'] ), 301 );
exit();
} else {
wp_redirect( 'http://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'], 301 );
exit();
}
}
}
add_action( 'template_redirect', 'bhww_ssl_template_redirect');
</code></pre>
<p>In this same function, I'd like to also redirect the <code>www</code> subdomain to non-www. I've found a good function <a href="https://stackoverflow.com/a/2079466/6647188">here</a>, but need help implementing it into my current function. I'd like to avoid doing this in <code>.htaccess</code>, but would welcome a solution there as well.</p>
|
[
{
"answer_id": 286474,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from your code I would refactor it like this:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {\n $url = $_SERVER['REQUEST_URI'];\n\n $not_allowed = array('https://www', 'https://');\n foreach($not_allowed as $types) {\n if(strpos($url, $types) === 0) {\n $redirect_url = str_replace($types, 'http://', $url); \n } \n }\n } else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Add it the <code>.htaccess</code> rules for the redirect www-> non - www</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]\nRewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]\n</code></pre>\n\n<p>Redirecting https->http</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n\n<p>But again for this to work you need to have a valid SSL or the \"Terror screen\" will be shown to users.</p>\n"
},
{
"answer_id": 286756,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>How to redirect <code>HTTPS</code> to <code>HTTP</code> and <code>www</code> to <code>non-www</code> URL with <code>.htaccess</code>:</h1>\n<ol>\n<li><p>First make sure <code>HTTPS</code> is working and valid. It's easy (and free) to do with <a href=\"https://letsencrypt.org\" rel=\"nofollow noreferrer\">Let's Encrypt</a> these days.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> Although you are redirecting <code>HTTPS</code> to <code>HTTP</code>, I'd recommend doing it the opposite, i.e. <code>HTTP</code> to <code>HTTPS</code>. Better for Security, SEO & Browser compatibility - popular browsers are increasingly making it difficult for <code>HTTP</code> sites.</p>\n</blockquote>\n</li>\n<li><p>Then make sure <code>.htaccess</code> and <code>mod_rewrite</code> module is working.</p>\n</li>\n<li><p>Then use the following CODE in the <code>.htaccess</code> file of your web root directory (if you are already using some rules there, adjust them accordingly with these new rules):</p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n\n RewriteCond %{HTTPS} =on [OR]\n RewriteCond %{HTTP_HOST} !^example\\.com$\n RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]\n\n # remaining htaccess mod_rewrite CODE for WordPress\n</IfModule>\n</code></pre>\n<blockquote>\n<p><em><strong>Note:</strong></em> Replace <code>example.com</code> with your own domain name.</p>\n</blockquote>\n</li>\n</ol>\n<hr />\n<h2>Why <code>.htaccess</code> solution is better:</h2>\n<p>It's better to do these sort of redirects with the web server. From your question, since your web server seems to be <code>Apache</code>, it's better to do with <code>.htaccess</code>. Why:</p>\n<ol>\n<li>It's faster.</li>\n<li>Your <code>functions.php</code> file remains cleaner & does what it's originally there for, i.e. Theme modifications.</li>\n<li>Changing the theme will not affect this.</li>\n<li>For every redirect, the entire WordPress codebase doesn't have to load twice - once before redirect & then after redirect.</li>\n</ol>\n"
},
{
"answer_id": 286765,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<p>Here, use this updated function to redirect a www site to non-www:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n $url = $_SERVER['REQUEST_URI'];\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $url, 'http' ) ) {\n if(strpos($url, 'https://') === 0) {\n $redirect_url = str_replace('https://', 'http://', $url); \n } \n } \n elseif ( TRUE == strpos( $url, 'www.') {\n $redirect_url = str_replace('www.', '', $url); \n } \n else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Let me know if this helps.</p>\n"
},
{
"answer_id": 287042,
"author": "Kyle Vassella",
"author_id": 112507,
"author_profile": "https://wordpress.stackexchange.com/users/112507",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect <code>https</code> to <code>http</code> and <code>www</code> to non-www. I placed the following code block inside of <code>functions.php</code>:</p>\n\n<pre><code>//check if https being used regardless of certificate\nfunction shapeSpace_check_https() { \n if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {\n return true; \n }\n return false;\n}\n\n\nfor ($x=0; $x<1; $x++) {\n //if https:// && www.\n if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only www.\n } elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only https://\n } elseif ( shapeSpace_check_https() ) {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit;\n break;\n }\n}\n</code></pre>\n\n<p>I don't think I need the <code>break;</code>'s, but I definitely need the <code>exit;</code>'s and I left the <code>break;</code>'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:</p>\n\n<p><a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a></p>\n"
}
] |
2017/11/20
|
[
"https://wordpress.stackexchange.com/questions/286464",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112507/"
] |
\*\*EDIT: I finally figured this out. Scroll down for my self-answered self-accepted answer (green check mark) \*\*
===================================================================================================================
I'm currently using `functions.php` to redirect `https` urls to `http` for a site which currently has no SSL certificate:
```
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
function bhww_ssl_template_redirect() {
if ( shapeSpace_check_https() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( preg_replace( '|^https://|', 'http://', $_SERVER['REQUEST_URI'] ), 301 );
exit();
} else {
wp_redirect( 'http://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'], 301 );
exit();
}
}
}
add_action( 'template_redirect', 'bhww_ssl_template_redirect');
```
In this same function, I'd like to also redirect the `www` subdomain to non-www. I've found a good function [here](https://stackoverflow.com/a/2079466/6647188), but need help implementing it into my current function. I'd like to avoid doing this in `.htaccess`, but would welcome a solution there as well.
|
Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect `https` to `http` and `www` to non-www. I placed the following code block inside of `functions.php`:
```
//check if https being used regardless of certificate
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
for ($x=0; $x<1; $x++) {
//if https:// && www.
if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only www.
} elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only https://
} elseif ( shapeSpace_check_https() ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
break;
}
}
```
I don't think I need the `break;`'s, but I definitely need the `exit;`'s and I left the `break;`'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:
<https://www.example.com> to <http://example.com>
<https://example.com> to <http://example.com>
<http://www.example.com> to <http://example.com>
|
286,467 |
<p>I want to hook into the subscriber role index.php page (wp-admin/index.php) to add some custom content outside of the widgets.</p>
<p>This admin_init works for all admin pages:</p>
<pre><code>add_action( 'init', 'test_init');
function test_init(){
add_action( 'admin_init', 'test_admin_init');
}
function test_admin_init() {
echo "Test Admin Init";
}
</code></pre>
<p>But this doesn't work for only subscribers:</p>
<pre><code>add_action('admin_init', 'add_to_dashboard');
function add_to_dashboard() {
if (current_user_can('subscriber') && is_admin()) {
add_action( 'admin_init', 'test_admin_init');
}
}
function test_admin_init() {
echo "Test Admin Init";
}
</code></pre>
<p>And how would this work for subscribers for only index.php and not profile.php?</p>
<p>Is this the wrong way to go about adding custom content to the subscriber's admin index.php page?</p>
|
[
{
"answer_id": 286474,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from your code I would refactor it like this:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {\n $url = $_SERVER['REQUEST_URI'];\n\n $not_allowed = array('https://www', 'https://');\n foreach($not_allowed as $types) {\n if(strpos($url, $types) === 0) {\n $redirect_url = str_replace($types, 'http://', $url); \n } \n }\n } else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Add it the <code>.htaccess</code> rules for the redirect www-> non - www</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]\nRewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]\n</code></pre>\n\n<p>Redirecting https->http</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n\n<p>But again for this to work you need to have a valid SSL or the \"Terror screen\" will be shown to users.</p>\n"
},
{
"answer_id": 286756,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>How to redirect <code>HTTPS</code> to <code>HTTP</code> and <code>www</code> to <code>non-www</code> URL with <code>.htaccess</code>:</h1>\n<ol>\n<li><p>First make sure <code>HTTPS</code> is working and valid. It's easy (and free) to do with <a href=\"https://letsencrypt.org\" rel=\"nofollow noreferrer\">Let's Encrypt</a> these days.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> Although you are redirecting <code>HTTPS</code> to <code>HTTP</code>, I'd recommend doing it the opposite, i.e. <code>HTTP</code> to <code>HTTPS</code>. Better for Security, SEO & Browser compatibility - popular browsers are increasingly making it difficult for <code>HTTP</code> sites.</p>\n</blockquote>\n</li>\n<li><p>Then make sure <code>.htaccess</code> and <code>mod_rewrite</code> module is working.</p>\n</li>\n<li><p>Then use the following CODE in the <code>.htaccess</code> file of your web root directory (if you are already using some rules there, adjust them accordingly with these new rules):</p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n\n RewriteCond %{HTTPS} =on [OR]\n RewriteCond %{HTTP_HOST} !^example\\.com$\n RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]\n\n # remaining htaccess mod_rewrite CODE for WordPress\n</IfModule>\n</code></pre>\n<blockquote>\n<p><em><strong>Note:</strong></em> Replace <code>example.com</code> with your own domain name.</p>\n</blockquote>\n</li>\n</ol>\n<hr />\n<h2>Why <code>.htaccess</code> solution is better:</h2>\n<p>It's better to do these sort of redirects with the web server. From your question, since your web server seems to be <code>Apache</code>, it's better to do with <code>.htaccess</code>. Why:</p>\n<ol>\n<li>It's faster.</li>\n<li>Your <code>functions.php</code> file remains cleaner & does what it's originally there for, i.e. Theme modifications.</li>\n<li>Changing the theme will not affect this.</li>\n<li>For every redirect, the entire WordPress codebase doesn't have to load twice - once before redirect & then after redirect.</li>\n</ol>\n"
},
{
"answer_id": 286765,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<p>Here, use this updated function to redirect a www site to non-www:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n $url = $_SERVER['REQUEST_URI'];\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $url, 'http' ) ) {\n if(strpos($url, 'https://') === 0) {\n $redirect_url = str_replace('https://', 'http://', $url); \n } \n } \n elseif ( TRUE == strpos( $url, 'www.') {\n $redirect_url = str_replace('www.', '', $url); \n } \n else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Let me know if this helps.</p>\n"
},
{
"answer_id": 287042,
"author": "Kyle Vassella",
"author_id": 112507,
"author_profile": "https://wordpress.stackexchange.com/users/112507",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect <code>https</code> to <code>http</code> and <code>www</code> to non-www. I placed the following code block inside of <code>functions.php</code>:</p>\n\n<pre><code>//check if https being used regardless of certificate\nfunction shapeSpace_check_https() { \n if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {\n return true; \n }\n return false;\n}\n\n\nfor ($x=0; $x<1; $x++) {\n //if https:// && www.\n if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only www.\n } elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only https://\n } elseif ( shapeSpace_check_https() ) {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit;\n break;\n }\n}\n</code></pre>\n\n<p>I don't think I need the <code>break;</code>'s, but I definitely need the <code>exit;</code>'s and I left the <code>break;</code>'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:</p>\n\n<p><a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a></p>\n"
}
] |
2017/11/20
|
[
"https://wordpress.stackexchange.com/questions/286467",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101490/"
] |
I want to hook into the subscriber role index.php page (wp-admin/index.php) to add some custom content outside of the widgets.
This admin\_init works for all admin pages:
```
add_action( 'init', 'test_init');
function test_init(){
add_action( 'admin_init', 'test_admin_init');
}
function test_admin_init() {
echo "Test Admin Init";
}
```
But this doesn't work for only subscribers:
```
add_action('admin_init', 'add_to_dashboard');
function add_to_dashboard() {
if (current_user_can('subscriber') && is_admin()) {
add_action( 'admin_init', 'test_admin_init');
}
}
function test_admin_init() {
echo "Test Admin Init";
}
```
And how would this work for subscribers for only index.php and not profile.php?
Is this the wrong way to go about adding custom content to the subscriber's admin index.php page?
|
Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect `https` to `http` and `www` to non-www. I placed the following code block inside of `functions.php`:
```
//check if https being used regardless of certificate
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
for ($x=0; $x<1; $x++) {
//if https:// && www.
if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only www.
} elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only https://
} elseif ( shapeSpace_check_https() ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
break;
}
}
```
I don't think I need the `break;`'s, but I definitely need the `exit;`'s and I left the `break;`'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:
<https://www.example.com> to <http://example.com>
<https://example.com> to <http://example.com>
<http://www.example.com> to <http://example.com>
|
286,512 |
<p>I had a website built on Woocommerce for me, but no longer have access to the Developer. I'm not a programmer so anything beyond CSS changes gives me quite a bit of problems. There is a piece of code that was working fine, but I have added an additional item to the site and now it only will fetch the most recent item added. I believe the problem is that get_posts is only collecting the latest product and I need it to collect all of them. Pretty sure I've narrowed it down to these two lines:</p>
<p><code>$products = get_posts(array('post_type' => 'product'));</code></p>
<p><code>$product = wc_get_product($products[0]->ID);</code></p>
<p>Does this need a loop? Sorry, I'm really not equipped to deal with this and it's really hard to find someone who can help me with a single question like this.</p>
|
[
{
"answer_id": 286474,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from your code I would refactor it like this:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {\n $url = $_SERVER['REQUEST_URI'];\n\n $not_allowed = array('https://www', 'https://');\n foreach($not_allowed as $types) {\n if(strpos($url, $types) === 0) {\n $redirect_url = str_replace($types, 'http://', $url); \n } \n }\n } else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Add it the <code>.htaccess</code> rules for the redirect www-> non - www</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]\nRewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]\n</code></pre>\n\n<p>Redirecting https->http</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n\n<p>But again for this to work you need to have a valid SSL or the \"Terror screen\" will be shown to users.</p>\n"
},
{
"answer_id": 286756,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>How to redirect <code>HTTPS</code> to <code>HTTP</code> and <code>www</code> to <code>non-www</code> URL with <code>.htaccess</code>:</h1>\n<ol>\n<li><p>First make sure <code>HTTPS</code> is working and valid. It's easy (and free) to do with <a href=\"https://letsencrypt.org\" rel=\"nofollow noreferrer\">Let's Encrypt</a> these days.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> Although you are redirecting <code>HTTPS</code> to <code>HTTP</code>, I'd recommend doing it the opposite, i.e. <code>HTTP</code> to <code>HTTPS</code>. Better for Security, SEO & Browser compatibility - popular browsers are increasingly making it difficult for <code>HTTP</code> sites.</p>\n</blockquote>\n</li>\n<li><p>Then make sure <code>.htaccess</code> and <code>mod_rewrite</code> module is working.</p>\n</li>\n<li><p>Then use the following CODE in the <code>.htaccess</code> file of your web root directory (if you are already using some rules there, adjust them accordingly with these new rules):</p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n\n RewriteCond %{HTTPS} =on [OR]\n RewriteCond %{HTTP_HOST} !^example\\.com$\n RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]\n\n # remaining htaccess mod_rewrite CODE for WordPress\n</IfModule>\n</code></pre>\n<blockquote>\n<p><em><strong>Note:</strong></em> Replace <code>example.com</code> with your own domain name.</p>\n</blockquote>\n</li>\n</ol>\n<hr />\n<h2>Why <code>.htaccess</code> solution is better:</h2>\n<p>It's better to do these sort of redirects with the web server. From your question, since your web server seems to be <code>Apache</code>, it's better to do with <code>.htaccess</code>. Why:</p>\n<ol>\n<li>It's faster.</li>\n<li>Your <code>functions.php</code> file remains cleaner & does what it's originally there for, i.e. Theme modifications.</li>\n<li>Changing the theme will not affect this.</li>\n<li>For every redirect, the entire WordPress codebase doesn't have to load twice - once before redirect & then after redirect.</li>\n</ol>\n"
},
{
"answer_id": 286765,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<p>Here, use this updated function to redirect a www site to non-www:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n $url = $_SERVER['REQUEST_URI'];\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $url, 'http' ) ) {\n if(strpos($url, 'https://') === 0) {\n $redirect_url = str_replace('https://', 'http://', $url); \n } \n } \n elseif ( TRUE == strpos( $url, 'www.') {\n $redirect_url = str_replace('www.', '', $url); \n } \n else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Let me know if this helps.</p>\n"
},
{
"answer_id": 287042,
"author": "Kyle Vassella",
"author_id": 112507,
"author_profile": "https://wordpress.stackexchange.com/users/112507",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect <code>https</code> to <code>http</code> and <code>www</code> to non-www. I placed the following code block inside of <code>functions.php</code>:</p>\n\n<pre><code>//check if https being used regardless of certificate\nfunction shapeSpace_check_https() { \n if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {\n return true; \n }\n return false;\n}\n\n\nfor ($x=0; $x<1; $x++) {\n //if https:// && www.\n if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only www.\n } elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only https://\n } elseif ( shapeSpace_check_https() ) {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit;\n break;\n }\n}\n</code></pre>\n\n<p>I don't think I need the <code>break;</code>'s, but I definitely need the <code>exit;</code>'s and I left the <code>break;</code>'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:</p>\n\n<p><a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112509/"
] |
I had a website built on Woocommerce for me, but no longer have access to the Developer. I'm not a programmer so anything beyond CSS changes gives me quite a bit of problems. There is a piece of code that was working fine, but I have added an additional item to the site and now it only will fetch the most recent item added. I believe the problem is that get\_posts is only collecting the latest product and I need it to collect all of them. Pretty sure I've narrowed it down to these two lines:
`$products = get_posts(array('post_type' => 'product'));`
`$product = wc_get_product($products[0]->ID);`
Does this need a loop? Sorry, I'm really not equipped to deal with this and it's really hard to find someone who can help me with a single question like this.
|
Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect `https` to `http` and `www` to non-www. I placed the following code block inside of `functions.php`:
```
//check if https being used regardless of certificate
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
for ($x=0; $x<1; $x++) {
//if https:// && www.
if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only www.
} elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only https://
} elseif ( shapeSpace_check_https() ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
break;
}
}
```
I don't think I need the `break;`'s, but I definitely need the `exit;`'s and I left the `break;`'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:
<https://www.example.com> to <http://example.com>
<https://example.com> to <http://example.com>
<http://www.example.com> to <http://example.com>
|
286,516 |
<p>I want to set a custom permalink for a specific wordpress page/post.</p>
<p>My expectation: <br>
1) Go to specific wordpress page/post edit view.<br>
2) Click edit permalink.<br>
3) Type in new permalink for the specific page/post and click save.<br></p>
<p>I have found a plugin name <a href="https://wordpress.org/plugins/custom-permalinks" rel="nofollow noreferrer">Custom Permalinks</a> which fits the exact need.
However, it seems not working in my environment (wordpress 4.8.x). When i use the new custom permalinks it display error 404.</p>
<p>Did i miss out any settings?</p>
<p>Note that if i use the custom permalink available by wordpress itself (which does not fit my needs), it works.</p>
<p>Any idea of how to have custom permalink for specific page/post.</p>
|
[
{
"answer_id": 286474,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": false,
"text": "<p>Taken from your code I would refactor it like this:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {\n $url = $_SERVER['REQUEST_URI'];\n\n $not_allowed = array('https://www', 'https://');\n foreach($not_allowed as $types) {\n if(strpos($url, $types) === 0) {\n $redirect_url = str_replace($types, 'http://', $url); \n } \n }\n } else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Add it the <code>.htaccess</code> rules for the redirect www-> non - www</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]\nRewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]\n</code></pre>\n\n<p>Redirecting https->http</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n</code></pre>\n\n<p>But again for this to work you need to have a valid SSL or the \"Terror screen\" will be shown to users.</p>\n"
},
{
"answer_id": 286756,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>How to redirect <code>HTTPS</code> to <code>HTTP</code> and <code>www</code> to <code>non-www</code> URL with <code>.htaccess</code>:</h1>\n<ol>\n<li><p>First make sure <code>HTTPS</code> is working and valid. It's easy (and free) to do with <a href=\"https://letsencrypt.org\" rel=\"nofollow noreferrer\">Let's Encrypt</a> these days.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> Although you are redirecting <code>HTTPS</code> to <code>HTTP</code>, I'd recommend doing it the opposite, i.e. <code>HTTP</code> to <code>HTTPS</code>. Better for Security, SEO & Browser compatibility - popular browsers are increasingly making it difficult for <code>HTTP</code> sites.</p>\n</blockquote>\n</li>\n<li><p>Then make sure <code>.htaccess</code> and <code>mod_rewrite</code> module is working.</p>\n</li>\n<li><p>Then use the following CODE in the <code>.htaccess</code> file of your web root directory (if you are already using some rules there, adjust them accordingly with these new rules):</p>\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n\n RewriteCond %{HTTPS} =on [OR]\n RewriteCond %{HTTP_HOST} !^example\\.com$\n RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]\n\n # remaining htaccess mod_rewrite CODE for WordPress\n</IfModule>\n</code></pre>\n<blockquote>\n<p><em><strong>Note:</strong></em> Replace <code>example.com</code> with your own domain name.</p>\n</blockquote>\n</li>\n</ol>\n<hr />\n<h2>Why <code>.htaccess</code> solution is better:</h2>\n<p>It's better to do these sort of redirects with the web server. From your question, since your web server seems to be <code>Apache</code>, it's better to do with <code>.htaccess</code>. Why:</p>\n<ol>\n<li>It's faster.</li>\n<li>Your <code>functions.php</code> file remains cleaner & does what it's originally there for, i.e. Theme modifications.</li>\n<li>Changing the theme will not affect this.</li>\n<li>For every redirect, the entire WordPress codebase doesn't have to load twice - once before redirect & then after redirect.</li>\n</ol>\n"
},
{
"answer_id": 286765,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 0,
"selected": false,
"text": "<p>Here, use this updated function to redirect a www site to non-www:</p>\n\n<pre><code>function bhww_ssl_template_redirect() {\n $redirect_url='';\n $url = $_SERVER['REQUEST_URI'];\n if ( shapeSpace_check_https() ) {\n if ( 0 === strpos( $url, 'http' ) ) {\n if(strpos($url, 'https://') === 0) {\n $redirect_url = str_replace('https://', 'http://', $url); \n } \n } \n elseif ( TRUE == strpos( $url, 'www.') {\n $redirect_url = str_replace('www.', '', $url); \n } \n else {\n $redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n }\n $redirect_url = !empty($redirect_url)?$redirect_url:$url;\n wp_redirect($redirect_url, 301 );\n exit(); \n }\n}\n</code></pre>\n\n<p>Let me know if this helps.</p>\n"
},
{
"answer_id": 287042,
"author": "Kyle Vassella",
"author_id": 112507,
"author_profile": "https://wordpress.stackexchange.com/users/112507",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect <code>https</code> to <code>http</code> and <code>www</code> to non-www. I placed the following code block inside of <code>functions.php</code>:</p>\n\n<pre><code>//check if https being used regardless of certificate\nfunction shapeSpace_check_https() { \n if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {\n return true; \n }\n return false;\n}\n\n\nfor ($x=0; $x<1; $x++) {\n //if https:// && www.\n if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only www.\n } elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);\n exit;\n break;\n //if only https://\n } elseif ( shapeSpace_check_https() ) {\n header('HTTP/1.1 301 Moved Permanently');\n header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);\n exit;\n break;\n }\n}\n</code></pre>\n\n<p>I don't think I need the <code>break;</code>'s, but I definitely need the <code>exit;</code>'s and I left the <code>break;</code>'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:</p>\n\n<p><a href=\"https://www.example.com\" rel=\"nofollow noreferrer\">https://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"https://example.com\" rel=\"nofollow noreferrer\">https://example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a> </p>\n\n<p><a href=\"http://www.example.com\" rel=\"nofollow noreferrer\">http://www.example.com</a> to <a href=\"http://example.com\" rel=\"nofollow noreferrer\">http://example.com</a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131671/"
] |
I want to set a custom permalink for a specific wordpress page/post.
My expectation:
1) Go to specific wordpress page/post edit view.
2) Click edit permalink.
3) Type in new permalink for the specific page/post and click save.
I have found a plugin name [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks) which fits the exact need.
However, it seems not working in my environment (wordpress 4.8.x). When i use the new custom permalinks it display error 404.
Did i miss out any settings?
Note that if i use the custom permalink available by wordpress itself (which does not fit my needs), it works.
Any idea of how to have custom permalink for specific page/post.
|
Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect `https` to `http` and `www` to non-www. I placed the following code block inside of `functions.php`:
```
//check if https being used regardless of certificate
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
for ($x=0; $x<1; $x++) {
//if https:// && www.
if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only www.
} elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
exit;
break;
//if only https://
} elseif ( shapeSpace_check_https() ) {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;
break;
}
}
```
I don't think I need the `break;`'s, but I definitely need the `exit;`'s and I left the `break;`'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:
<https://www.example.com> to <http://example.com>
<https://example.com> to <http://example.com>
<http://www.example.com> to <http://example.com>
|
286,530 |
<p>You can use <code>wp_editor</code> to display the wordpress rich editor. How can I display the shorter version (Please see the screenshot, I need that) of <code>wp_editor</code>? </p>
<p><a href="https://i.stack.imgur.com/53ubM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/53ubM.png" alt="enter image description here"></a></p>
|
[
{
"answer_id": 286565,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 2,
"selected": false,
"text": "<p>You will want to pass some parameters into your <code>$settings</code> array for <code>wp_editor()</code> that only tells it to display the quicktags for <code>strong</code>,<code>em</code>,<code>ul</code>,<code>ol</code>, and <code>link</code> per your screenshot.</p>\n\n<p>I didn't have time to test it, but this code should give you want you want:</p>\n\n<pre><code>$settings = array(\n // Any previous settings you are currently using \n 'quicktags' => array( 'buttons' => 'strong,em,ul,ol,link' ),\n);\n\nwp_editor( '', 'my-short-editor', $settings );\n</code></pre>\n\n<p>You can replace <code>'my-short-editor'</code> with anything but keep in mind this will be the <code>id</code> attribute for the resulting editor when rendered.</p>\n"
},
{
"answer_id": 286620,
"author": "Niket Joshi",
"author_id": 122094,
"author_profile": "https://wordpress.stackexchange.com/users/122094",
"pm_score": 2,
"selected": false,
"text": "<p>this is following code for your editor shorter version.</p>\n\n<pre><code> $settings = array(\n 'quicktags' => array('buttons' => 'em,strong,link',),\n 'quicktags' => true,\n 'tinymce' => true,\n'textarea_rows' => 20,\n 'classes' => 'yourclass',\n);\n</code></pre>\n\n<p>or when you're calling the wp_editor:</p>\n\n<pre><code><?php wp_editor( $content, $editor_id, $settings = array('editor_class'=>'yourclass') ); ?>\n</code></pre>\n\n<p>Then just set width in css:</p>\n\n<pre><code> .yourclass {\n width: 400px !important; //add !important if your style is being overriden \n} \n</code></pre>\n\n<p>hope this will help you. For more <a href=\"https://wordpress.stackexchange.com/questions/114311/remove-specific-buttons-from-wp-editor\">URL 1</a>, <a href=\"https://wordpress.stackexchange.com/questions/112441/how-to-set-wysiwyg-editor-width-within-wp-editor-function\">URL 2</a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
] |
You can use `wp_editor` to display the wordpress rich editor. How can I display the shorter version (Please see the screenshot, I need that) of `wp_editor`?
[](https://i.stack.imgur.com/53ubM.png)
|
You will want to pass some parameters into your `$settings` array for `wp_editor()` that only tells it to display the quicktags for `strong`,`em`,`ul`,`ol`, and `link` per your screenshot.
I didn't have time to test it, but this code should give you want you want:
```
$settings = array(
// Any previous settings you are currently using
'quicktags' => array( 'buttons' => 'strong,em,ul,ol,link' ),
);
wp_editor( '', 'my-short-editor', $settings );
```
You can replace `'my-short-editor'` with anything but keep in mind this will be the `id` attribute for the resulting editor when rendered.
|
286,534 |
<p>I'm looking for how hide or remove Link Relationship (XFN) from Menus tab (In red on the picture below)</p>
<p><a href="https://i.stack.imgur.com/ReqAc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ReqAc.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 286565,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 2,
"selected": false,
"text": "<p>You will want to pass some parameters into your <code>$settings</code> array for <code>wp_editor()</code> that only tells it to display the quicktags for <code>strong</code>,<code>em</code>,<code>ul</code>,<code>ol</code>, and <code>link</code> per your screenshot.</p>\n\n<p>I didn't have time to test it, but this code should give you want you want:</p>\n\n<pre><code>$settings = array(\n // Any previous settings you are currently using \n 'quicktags' => array( 'buttons' => 'strong,em,ul,ol,link' ),\n);\n\nwp_editor( '', 'my-short-editor', $settings );\n</code></pre>\n\n<p>You can replace <code>'my-short-editor'</code> with anything but keep in mind this will be the <code>id</code> attribute for the resulting editor when rendered.</p>\n"
},
{
"answer_id": 286620,
"author": "Niket Joshi",
"author_id": 122094,
"author_profile": "https://wordpress.stackexchange.com/users/122094",
"pm_score": 2,
"selected": false,
"text": "<p>this is following code for your editor shorter version.</p>\n\n<pre><code> $settings = array(\n 'quicktags' => array('buttons' => 'em,strong,link',),\n 'quicktags' => true,\n 'tinymce' => true,\n'textarea_rows' => 20,\n 'classes' => 'yourclass',\n);\n</code></pre>\n\n<p>or when you're calling the wp_editor:</p>\n\n<pre><code><?php wp_editor( $content, $editor_id, $settings = array('editor_class'=>'yourclass') ); ?>\n</code></pre>\n\n<p>Then just set width in css:</p>\n\n<pre><code> .yourclass {\n width: 400px !important; //add !important if your style is being overriden \n} \n</code></pre>\n\n<p>hope this will help you. For more <a href=\"https://wordpress.stackexchange.com/questions/114311/remove-specific-buttons-from-wp-editor\">URL 1</a>, <a href=\"https://wordpress.stackexchange.com/questions/112441/how-to-set-wysiwyg-editor-width-within-wp-editor-function\">URL 2</a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286534",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] |
I'm looking for how hide or remove Link Relationship (XFN) from Menus tab (In red on the picture below)
[](https://i.stack.imgur.com/ReqAc.jpg)
|
You will want to pass some parameters into your `$settings` array for `wp_editor()` that only tells it to display the quicktags for `strong`,`em`,`ul`,`ol`, and `link` per your screenshot.
I didn't have time to test it, but this code should give you want you want:
```
$settings = array(
// Any previous settings you are currently using
'quicktags' => array( 'buttons' => 'strong,em,ul,ol,link' ),
);
wp_editor( '', 'my-short-editor', $settings );
```
You can replace `'my-short-editor'` with anything but keep in mind this will be the `id` attribute for the resulting editor when rendered.
|
286,547 |
<p>Is there a way to bulk add one word at the end of each URL for posts? I have around 3500 posts and it would be time consuming to add to each one.</p>
<p>For example URL's are </p>
<pre><code>www.example.com/my-post/
www.examle.com/new-post/
</code></pre>
<p>And I want to add one word to end of URL</p>
<pre><code>www.example.com/my-post-word/
www.examle.com/new-post-word/
</code></pre>
<p>Is there MySql script to do such thing?</p>
|
[
{
"answer_id": 286549,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 2,
"selected": true,
"text": "<p>Here is your code:</p>\n\n<pre><code>if ( isset($_GET['slug-update']) ) {\n\n $posts = get_posts();\n\n foreach($posts as $singlepost) {\n if($singlepost->post_status === 'publish'){\n $post_id = $singlepost->ID;\n $current_slug = $singlepost->post_name;\n $updated_slug = $current_slug . '-word';\n }\n\n wp_update_post( array(\n 'ID' => $post_id,\n 'post_name' => $updated_slug ) );\n }\n\n die('Slug Updated'); \n}\n</code></pre>\n\n<p>Add this to your theme's function.php. Then run this with <code>www.example.com/?slug-update</code></p>\n\n<p>P.S. this will only update the default post type 'post' (backup the database to be secure)</p>\n\n<p>Let me know if this helped.</p>\n"
},
{
"answer_id": 288960,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you just add it inside the WP admin <a href=\"https://codex.wordpress.org/Settings_Permalinks_Screen\" rel=\"nofollow noreferrer\">permalink settings</a>?\n<a href=\"https://i.stack.imgur.com/HBPhp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HBPhp.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74294/"
] |
Is there a way to bulk add one word at the end of each URL for posts? I have around 3500 posts and it would be time consuming to add to each one.
For example URL's are
```
www.example.com/my-post/
www.examle.com/new-post/
```
And I want to add one word to end of URL
```
www.example.com/my-post-word/
www.examle.com/new-post-word/
```
Is there MySql script to do such thing?
|
Here is your code:
```
if ( isset($_GET['slug-update']) ) {
$posts = get_posts();
foreach($posts as $singlepost) {
if($singlepost->post_status === 'publish'){
$post_id = $singlepost->ID;
$current_slug = $singlepost->post_name;
$updated_slug = $current_slug . '-word';
}
wp_update_post( array(
'ID' => $post_id,
'post_name' => $updated_slug ) );
}
die('Slug Updated');
}
```
Add this to your theme's function.php. Then run this with `www.example.com/?slug-update`
P.S. this will only update the default post type 'post' (backup the database to be secure)
Let me know if this helped.
|
286,551 |
<p>I have added a custom url to the widget image in the new WP 4.9. Now I want to add an onclick event to the link.</p>
<p>The a tag looks like this</p>
<pre><code><a href="http://domain.com/this-is-a-page" class="" rel="" target=""></a>
</code></pre>
<p>And I want to have it like this</p>
<pre><code><a href="http://domain.com/this-is-a-page" onclick="ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');"></a>
</code></pre>
<p>How can I do this?</p>
|
[
{
"answer_id": 286553,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": true,
"text": "<p>I would use the <a href=\"https://support.google.com/tagmanager/answer/6106961?hl=en\" rel=\"nofollow noreferrer\">Google Tag Manager firing options</a>:</p>\n\n<p>Or</p>\n\n<p>Old school jQuery solution:</p>\n\n<pre><code> function($){\n $('.widget_class').click(function() {\n ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');\n });\n })(jQuery);\n</code></pre>\n\n<p>Now you just add a class name to your links.</p>\n"
},
{
"answer_id": 286566,
"author": "meDeepakJain",
"author_id": 85593,
"author_profile": "https://wordpress.stackexchange.com/users/85593",
"pm_score": 0,
"selected": false,
"text": "<p>Each widget do have their own unique IDs assigned to them. You may use jQuery to access that particular widget box with respective ID and perform the task accordingly.</p>\n\n<p>Additional note: If your widget don't have any unique id then go to your functions.php and modify the code of widget declaration. Here is the WP codex link for your reference \n<a href=\"https://codex.wordpress.org/Sidebars\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Sidebars</a> </p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286551",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39284/"
] |
I have added a custom url to the widget image in the new WP 4.9. Now I want to add an onclick event to the link.
The a tag looks like this
```
<a href="http://domain.com/this-is-a-page" class="" rel="" target=""></a>
```
And I want to have it like this
```
<a href="http://domain.com/this-is-a-page" onclick="ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');"></a>
```
How can I do this?
|
I would use the [Google Tag Manager firing options](https://support.google.com/tagmanager/answer/6106961?hl=en):
Or
Old school jQuery solution:
```
function($){
$('.widget_class').click(function() {
ga('send', 'event', 'Sidebar Image', 'Promo Image', 'Clicked');
});
})(jQuery);
```
Now you just add a class name to your links.
|
286,599 |
<p>I created a new tab called "Videos" inside of the BuddyPress Profile page. This tab contains all video posts added by that user. The problem is that it only shows the first 12 posts and the pagination does not show up. I did try to include the pagination code provided by the theme but to no avail.</p>
<p>Notes:</p>
<ul>
<li><p>I am using a theme called "VideoTube"</p></li>
<li><p>The post loop to be paginated is from a custom post type called "video"</p></li>
<li><p>The original pagination code provided by the theme is <code><?php do_action( 'mars_pagination', null );?></code></p></li>
<li><p>The code below is pulled from my functions.php file in the child theme folder.</p></li>
</ul>
<p>Thank you in advance for all your help :D</p>
<p>Code:</p>
<pre><code> <?php function my_videos_screen_content() {
?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<div class="row video-section meta-maxwidth-230">
<?php
$args = array(
'post_type' => array( 'video' ),
'author' => bp_displayed_user_id(),
'posts_per_page' => get_option( 'posts_per_page' )
);
$author_videos = new WP_Query( $args );
if ( $author_videos->have_posts() ) : while ( $author_videos->have_posts() ) : $author_videos->the_post();
get_template_part( 'loop', 'video' );
endwhile; ?>
</div>
<?php do_action( 'mars_pagination', null );?>
<?php wp_reset_postdata();
endif; ?>
</div>
</div>
</div>
</div>
<?php }
</code></pre>
<p>So I figured out how to show the pagination, with the following code.
The problem is when I click on the next page, it brings me to a 404 page. But when I manually visit a custom URL it does show the second page correctly, here are both examples:</p>
<p><strong>404 Version:</strong></p>
<p>This is the url structure that is generated by this pagination code</p>
<p>www.website.com/members/username/my-videos/page/2/</p>
<p><strong>Working Version:</strong></p>
<p>This is a manual url I found to be working</p>
<p>www.website.com/members/username/my-videos/?page=2</p>
<p>Question is, how to get it to work with the first version (/page/2/)</p>
<p><strong>CODE:</strong></p>
<pre><code> <?php function my_videos_screen_content() {
echo 'We are currently working on this section, some content may not appear properly. Thank you for your patience.'; ?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<div class="row video-section meta-maxwidth-230">
<?php
$custom_query_args = array(
'post_type' => 'video',
'author' => bp_displayed_user_id(),
'posts_per_page' => get_option( 'posts_per_page' )
);
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$custom_query = new WP_Query( $custom_query_args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post();
get_template_part( 'loop', 'video' );
endwhile; ?>
</div>
<?php endif;
wp_reset_postdata(); ?>
<?php // Custom query loop pagination
previous_posts_link( 'Newer Videos' );
next_posts_link( 'Older Videos', $custom_query->max_num_pages );?>
<?php // Reset main query object
$wp_query = NULL;
$wp_query = $temp_query; ?>
</div>
</div><!-- /.row -->
</div>
</div><!-- /.container -->
</code></pre>
<p>
|
[
{
"answer_id": 286554,
"author": "Welcher",
"author_id": 27210,
"author_profile": "https://wordpress.stackexchange.com/users/27210",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on your setup, there may be caching in place that would not be accounted for when accessing the database directly.</p>\n\n<p>Is it possible for you to run <code>set_theme_mod</code> with the new value instead - via your functions.php file for example?</p>\n"
},
{
"answer_id": 286562,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 3,
"selected": true,
"text": "<p>The data is serialized.</p>\n\n<p>In order to edit it, you need to unserialize it, edit, then serialize again, and save.</p>\n\n<p>You can do that with PHP.</p>\n\n<p>Check <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow noreferrer\">serialize</a> and <a href=\"http://php.net/manual/en/function.unserialize.php\" rel=\"nofollow noreferrer\">unserialize</a>.</p>\n\n<p>You can check this tool as well: <a href=\"http://serializededitor.com\" rel=\"nofollow noreferrer\">serializededitor.com</a></p>\n"
},
{
"answer_id": 320395,
"author": "SherylHohman",
"author_id": 109770,
"author_profile": "https://wordpress.stackexchange.com/users/109770",
"pm_score": 1,
"selected": false,
"text": "<p>I was able to paste a \"broken\" serialized database entry into this online tool:<br>\n<a href=\"https://itask.software/tools/serialization-fixer.php\" rel=\"nofollow noreferrer\">https://itask.software/tools/serialization-fixer.php</a></p>\n\n<ol>\n<li>Paste a broken serialization string into the box. </li>\n<li>Click \"Fix\". It counts characters for you, outputting the fixed version in the box below. </li>\n<li>Copy-paste the corrected version into database table to fix.</li>\n</ol>\n\n<p>In my case I had directly edited serialized text, which broke the character count, and for whatever reason, I had trouble getting the count right by hand.<br>\nThe online tool properly counted characters and updated the serialization string for me.</p>\n\n<p>Another useful online tool I found shows the PHP unserialized version of the string, which is nice.<br>\nBut what I found useful for testing, is that it shows an error message above the above the unserialized output, if the character counts are wrong.<br>\nIf no message shows, then your serialized string is (likely) correct.<br>\n<a href=\"http://unserialize.onlinephpfunctions.com/\" rel=\"nofollow noreferrer\">http://unserialize.onlinephpfunctions.com/</a></p>\n"
},
{
"answer_id": 379573,
"author": "gtamborero",
"author_id": 52236,
"author_profile": "https://wordpress.stackexchange.com/users/52236",
"pm_score": 0,
"selected": false,
"text": "<p>I tried with serialize/unserialize but no way... So I finaly search thru the wordpress theme options to find where was the data I need to modify. Changing it inside the WordPress backend is the only way I have find to solve the problem. Not nice, but it works!</p>\n"
},
{
"answer_id": 387393,
"author": "Gavin",
"author_id": 63238,
"author_profile": "https://wordpress.stackexchange.com/users/63238",
"pm_score": 0,
"selected": false,
"text": "<p>This is a nice tool that lets you do serialized string search and replace within your database: <a href=\"https://interconnectit.com/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/search-and-replace-for-wordpress-databases/</a></p>\n"
}
] |
2017/11/21
|
[
"https://wordpress.stackexchange.com/questions/286599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131892/"
] |
I created a new tab called "Videos" inside of the BuddyPress Profile page. This tab contains all video posts added by that user. The problem is that it only shows the first 12 posts and the pagination does not show up. I did try to include the pagination code provided by the theme but to no avail.
Notes:
* I am using a theme called "VideoTube"
* The post loop to be paginated is from a custom post type called "video"
* The original pagination code provided by the theme is `<?php do_action( 'mars_pagination', null );?>`
* The code below is pulled from my functions.php file in the child theme folder.
Thank you in advance for all your help :D
Code:
```
<?php function my_videos_screen_content() {
?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<div class="row video-section meta-maxwidth-230">
<?php
$args = array(
'post_type' => array( 'video' ),
'author' => bp_displayed_user_id(),
'posts_per_page' => get_option( 'posts_per_page' )
);
$author_videos = new WP_Query( $args );
if ( $author_videos->have_posts() ) : while ( $author_videos->have_posts() ) : $author_videos->the_post();
get_template_part( 'loop', 'video' );
endwhile; ?>
</div>
<?php do_action( 'mars_pagination', null );?>
<?php wp_reset_postdata();
endif; ?>
</div>
</div>
</div>
</div>
<?php }
```
So I figured out how to show the pagination, with the following code.
The problem is when I click on the next page, it brings me to a 404 page. But when I manually visit a custom URL it does show the second page correctly, here are both examples:
**404 Version:**
This is the url structure that is generated by this pagination code
www.website.com/members/username/my-videos/page/2/
**Working Version:**
This is a manual url I found to be working
www.website.com/members/username/my-videos/?page=2
Question is, how to get it to work with the first version (/page/2/)
**CODE:**
```
<?php function my_videos_screen_content() {
echo 'We are currently working on this section, some content may not appear properly. Thank you for your patience.'; ?>
<div class="container">
<div class="row">
<div class="col-sm-8">
<div class="row video-section meta-maxwidth-230">
<?php
$custom_query_args = array(
'post_type' => 'video',
'author' => bp_displayed_user_id(),
'posts_per_page' => get_option( 'posts_per_page' )
);
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$custom_query = new WP_Query( $custom_query_args );
$temp_query = $wp_query;
$wp_query = NULL;
$wp_query = $custom_query;
if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post();
get_template_part( 'loop', 'video' );
endwhile; ?>
</div>
<?php endif;
wp_reset_postdata(); ?>
<?php // Custom query loop pagination
previous_posts_link( 'Newer Videos' );
next_posts_link( 'Older Videos', $custom_query->max_num_pages );?>
<?php // Reset main query object
$wp_query = NULL;
$wp_query = $temp_query; ?>
</div>
</div><!-- /.row -->
</div>
</div><!-- /.container -->
```
|
The data is serialized.
In order to edit it, you need to unserialize it, edit, then serialize again, and save.
You can do that with PHP.
Check [serialize](http://php.net/manual/en/function.serialize.php) and [unserialize](http://php.net/manual/en/function.unserialize.php).
You can check this tool as well: [serializededitor.com](http://serializededitor.com)
|
286,618 |
<p>I have a wordpress setup which has more than 300 categories.</p>
<p>Now I have requirement to give some flexibility to choose the categories. In that case I initially pre-ticked all the categories, if someone need to exclude a category they can deselect it. </p>
<p>Now the problem I am facing is how to give accurate results according the category selection.</p>
<p>My first approach was just exclude all the deselect categories as bellow,</p>
<p>eg: exclude 10,11,12 categories</p>
<pre><code>$args = array(
'category__not_in' => array('10','11','12')
);
</code></pre>
<p>Let's say I have a post which was ticked under <code>category 12 & 13</code>. From above code I will not get that post as a result as it is excluding posts under the <code>category 12</code>. But ideally it should be in the results as <code>category 13</code> was not deselected.</p>
<p>As I solution I could use <code>'category__in'</code> option with all selected category ids. But my worry is the list would be very long even-though it is coming programmatically, I am not sure about the <code>wp_query</code> overhead as I have more than 300 categories.</p>
<p>Anyone has a better idea how to solve this issue.</p>
|
[
{
"answer_id": 286717,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 2,
"selected": false,
"text": "<p>Why are you pre-ticking all the categories? Isn't it easier to display all the results and at the same time have the categories all un-ticked? Then when the user selects a few (who's going to select 300 categories?) you can run a query with <code>category__in</code>.</p>\n"
},
{
"answer_id": 286952,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": false,
"text": "<p>As you probably know it, categories are taxonomies. When you use the arguments such as <code>category__in</code>, it will add a tax query to your <code>WP_Query()</code>. So, your situation would be something like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 12 ),\n 'operator' => 'IN',\n ),\n array(\n 'taxonomy' => 'category',\n 'field' => 'term_id',\n 'terms' => array( 11, 12, 13 ),\n 'operator' => 'NOT IN',\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>I wouldn't think of performance issues here. This is most likely your only solution, if you don't want to directly query the posts from database by using a SQL query ( This might improve the performance a bit ).</p>\n"
},
{
"answer_id": 286953,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 1,
"selected": false,
"text": "<p>Am not sure but I think you cannot do this using the default behavior/options of <code>WP_Query</code>. So maybe a work around will be to implement a function that will do this test for you after selecting all the posts.</p>\n\n<p>Of course, the drawback of this method is that you have to first select all the posts then filter them, but it can be a solution for you problem. So you can do somthing like this :</p>\n\n<pre><code><?php \n\nfunction test_categorie($cats,$ex_cats) {\n\n $test = false; //we consider that this post is excluded until we found a category that doesn't belong to the array\n foreach ($cats as $cat){\n if(!in_array(intval($cat->term_id),$ex_cats)) {\n $test = true;\n //We can exit the loop as this post have at least one category not excluded so we can consider it\n break;\n }\n\n }\n return $test;\n}\n//Define the excluded categorie here\n$exclude_cat = array(11,12,13);\n\n$args = array(\n 'posts_per_page' => -1,\n 'post_type' => 'post',\n);\n\n$the_query = new WP_Query($args );\nif ( $the_query->have_posts() ) :\n while ( $the_query->have_posts() ) : $the_query->the_post(); \n //we do our test, if(false) we don't consider the post and we continue to the next\n if(!test_categorie(get_the_category(),$exclude_cat))\n continue;\n\n /* \n Add you code here\n */\n\n endwhile;\n wp_reset_postdata(); \nendif;\n\n?>\n</code></pre>\n"
},
{
"answer_id": 287265,
"author": "Alexander Taranenko",
"author_id": 132325,
"author_profile": "https://wordpress.stackexchange.com/users/132325",
"pm_score": 1,
"selected": false,
"text": "<p>try this one.\nI guess this is a bit dirty , but it works for me good!</p>\n\n<pre><code> $skills = get_user_meta($curr_id , 'designer_skills');\n $skills = array_map('intval', explode(',' , $skills[0]));\n $args = array(\n 'numberposts' => -1,\n 'post_type' => 'project',\n 'meta_query' => array(\n 'relation' => 'AND',\n array(\n 'key' => 'status',\n 'compare' => '=',\n 'value' => 'open'\n ),\n array(\n 'key' => 'payment_status',\n 'compare' => '=',\n 'value' => true\n )\n )\n );\n $posts = get_posts( $args );\n if ($posts) {\n $count = 0;\n foreach ($posts as $project) {\n if (in_array(get_the_terms( $project->ID, 'projects')[0] -> term_id , $skills)){\n //implement your own code here\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 287337,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>Let's assume that we have 4 posts and 4 categories.</p>\n\n<pre><code>+----+--------+\n| ID | Post |\n+----+--------+\n| 1 | Test 1 |\n| 2 | Test 2 |\n| 3 | Test 3 |\n| 4 | Test 4 |\n+----+--------+\n\n+----+------------+\n| ID | Category |\n+----+------------+\n| 1 | Category 1 |\n| 2 | Category 2 |\n| 3 | Category 3 |\n| 4 | Category 4 |\n+----+------------+\n\n+--------+------------------------+\n| Post | Category |\n+--------+------------------------+\n| Test 1 | Category 1, Category 2 |\n| Test 2 | Category 2 |\n| Test 3 | Category 3 |\n| Test 4 | Category 4 |\n+--------+------------------------+\n</code></pre>\n\n<p>If I understood your question correctly, you want to get <code>Test 1</code> post using <code>category__not_in</code> parameter. Arguments to your query will look's like:</p>\n\n<pre><code>$args = array(\n 'category__not_in' => array(2, 3, 4)\n);\n</code></pre>\n\n<p>The problem with <code>category__not_in</code> is that it produce <code>NOT IN SELECT</code> SQL query. </p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID\nFROM wp_posts\nWHERE 1=1\n AND (wp_posts.ID NOT IN\n ( SELECT object_id\n FROM wp_term_relationships\n WHERE term_taxonomy_id IN (2, 3, 4) ))\n AND wp_posts.post_type = 'post'\n AND (wp_posts.post_status = 'publish'\n OR wp_posts.post_status = 'private')\nGROUP BY wp_posts.ID\nORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p><code>NOT IN SELECT</code> will exclude all posts including <code>Test 1</code>. If only this SQL would use <code>JOIN</code> instead of <code>NOT IN SELECT</code> this will work.</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID\nFROM wp_posts\nLEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)\nWHERE 1=1\n AND (wp_term_relationships.term_taxonomy_id NOT IN (2, 3, 4))\n AND wp_posts.post_type = 'post'\n AND (wp_posts.post_status = 'publish'\n OR wp_posts.post_status = 'private')\nGROUP BY wp_posts.ID\nORDER BY wp_posts.post_date DESC LIMIT 0, 10\n</code></pre>\n\n<p>Above SQL will return only <code>Test 1</code> post. We can make a little trick to produce such a query using WP_Query class. Instead of using <code>category__not_in</code> parameter replace it with <code>category__in</code> parameter and add <code>post_where</code> filter which will modify SQL directly to our purpose.</p>\n\n<pre><code>function wp_286618_get_posts() {\n\n $query = new WP_Query( array(\n 'post_type' => 'post',\n 'category__in' => array( 2, 3, 4 ) // Use `category__in` to force JOIN SQL query.\n ) );\n\n return $query->get_posts();\n}\n\nfunction wp_286618_replace_in_operator($where, $object) {\n\n $search = 'term_taxonomy_id IN'; // Search IN operator created by `category__in` parameter.\n $replace = 'term_taxonomy_id NOT IN'; // Replace IN operator to NOT IN\n\n $where = str_replace($search, $replace, $where);\n\n return $where;\n}\n\nadd_filter( 'posts_where', 'wp_286618_replace_in_operator', 10, 2 ); // Add filter to replace IN operator\n\n$posts = wp_286618_get_posts(); // Will return only Test 1 post\n\nremove_filter( 'posts_where', 'wp_286618_replace_in_operator', 10, 2 ); // Remove filter to not affect other queries\n</code></pre>\n\n<p>The advantage of this solution over others is that I don't need to know other categories ID, and it will keep your post loop clean.</p>\n"
}
] |
2017/11/22
|
[
"https://wordpress.stackexchange.com/questions/286618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68403/"
] |
I have a wordpress setup which has more than 300 categories.
Now I have requirement to give some flexibility to choose the categories. In that case I initially pre-ticked all the categories, if someone need to exclude a category they can deselect it.
Now the problem I am facing is how to give accurate results according the category selection.
My first approach was just exclude all the deselect categories as bellow,
eg: exclude 10,11,12 categories
```
$args = array(
'category__not_in' => array('10','11','12')
);
```
Let's say I have a post which was ticked under `category 12 & 13`. From above code I will not get that post as a result as it is excluding posts under the `category 12`. But ideally it should be in the results as `category 13` was not deselected.
As I solution I could use `'category__in'` option with all selected category ids. But my worry is the list would be very long even-though it is coming programmatically, I am not sure about the `wp_query` overhead as I have more than 300 categories.
Anyone has a better idea how to solve this issue.
|
As you probably know it, categories are taxonomies. When you use the arguments such as `category__in`, it will add a tax query to your `WP_Query()`. So, your situation would be something like this:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 12 ),
'operator' => 'IN',
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 11, 12, 13 ),
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
```
I wouldn't think of performance issues here. This is most likely your only solution, if you don't want to directly query the posts from database by using a SQL query ( This might improve the performance a bit ).
|
286,632 |
<pre><code>$args = array(
'post_type' => 'listing',
'order' => 'ASC',
'hide_empty' => false,
'parent' => 0,
);
$listCatTerms = get_terms( 'listing-category',$args);
if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
foreach ( $listCatTerms as $term ) {
echo '<li class="lp-wrap-cats" data-catid="'.$term->term_id.'">'.$catIcon.'<span class="lp-s-cat">'.$term->name.'</span></li>';
$defaultCats .='<li class="lp-wrap-cats" data-catid="'.$term->term_id.'">'.$catIcon.'<span class="lp-s-cat">'.$term->name.'</span></li>';
}
}
</code></pre>
|
[
{
"answer_id": 286641,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 1,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach ( $listCatTerms as $term ) {\n echo '<li>'.$term->name.'</li>';\n $child_terms = get_categories( array(\n 'parent' => $term->term_id,\n 'hide_empty' => 0 ));\n //var_dump($child_terms);\n echo \"<ul>\";\n foreach($child_terms as $child_term){\n echo '<li> -- '.$child_term->name.'</li>';\n }\n echo \"</ul><br>\";\n }\n echo \"</ul>\"; \n } \n</code></pre>\n\n<p>This should display the name of parent category and all its child category after.</p>\n"
},
{
"answer_id": 286656,
"author": "Sourav Kundu",
"author_id": 120713,
"author_profile": "https://wordpress.stackexchange.com/users/120713",
"pm_score": 0,
"selected": false,
"text": "<p>You Can Try This Code</p>\n\n<pre>\n$getterms=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ));\nforeach( $getterms as $parent_term ) \n{\n echo $parent_term->name;\n $getpchild=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );\n foreach( $getpchild as $child_term ) \n {\n echo $child_term->name;\n }\n\n}\n</pre>\n"
},
{
"answer_id": 286668,
"author": "Lovin Nagi",
"author_id": 102970,
"author_profile": "https://wordpress.stackexchange.com/users/102970",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach($listCatTerms as $listCatTerm) {\n\n //parent categories\n echo '<li>'.$listCatTerm->name.'</li>';\n\n //get childern term ID \n $term_children = get_term_children( $listCatTerm->term_id, 'listing-category' );\n foreach ( $term_children as $child ) { \n //Get all Term data from database by Term field and data.\n $term = get_term_by( 'id', $child, 'listing-category' );\n //childern categories of its parent category\n echo '<li class=\"lp-wrap-cats\">'.$term->name.'</li>';\n }\n }\n echo \"</ul>\"; \n }\n</code></pre>\n"
}
] |
2017/11/22
|
[
"https://wordpress.stackexchange.com/questions/286632",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102970/"
] |
```
$args = array(
'post_type' => 'listing',
'order' => 'ASC',
'hide_empty' => false,
'parent' => 0,
);
$listCatTerms = get_terms( 'listing-category',$args);
if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
foreach ( $listCatTerms as $term ) {
echo '<li class="lp-wrap-cats" data-catid="'.$term->term_id.'">'.$catIcon.'<span class="lp-s-cat">'.$term->name.'</span></li>';
$defaultCats .='<li class="lp-wrap-cats" data-catid="'.$term->term_id.'">'.$catIcon.'<span class="lp-s-cat">'.$term->name.'</span></li>';
}
}
```
|
Here you go:
```
$args = array(
'post_type' => 'listing',
'order' => 'ASC',
'hide_empty' => false,
'parent' => 0,
);
$listCatTerms = get_terms( 'listing-category',$args);
if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
echo "<ul>";
foreach ( $listCatTerms as $term ) {
echo '<li>'.$term->name.'</li>';
$child_terms = get_categories( array(
'parent' => $term->term_id,
'hide_empty' => 0 ));
//var_dump($child_terms);
echo "<ul>";
foreach($child_terms as $child_term){
echo '<li> -- '.$child_term->name.'</li>';
}
echo "</ul><br>";
}
echo "</ul>";
}
```
This should display the name of parent category and all its child category after.
|
286,660 |
<p>I crated a footer.php and a corresponding customFooter.php. It looked great until I added header.php and customHeader.css. Now the 2 custom css files are overlaping. For example: some of the <code><img></code> are not aligned properly, due to the alignment of the pther css file.
Is it possible to restrict certain css file only to a specific pphp file??</p>
|
[
{
"answer_id": 286641,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 1,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach ( $listCatTerms as $term ) {\n echo '<li>'.$term->name.'</li>';\n $child_terms = get_categories( array(\n 'parent' => $term->term_id,\n 'hide_empty' => 0 ));\n //var_dump($child_terms);\n echo \"<ul>\";\n foreach($child_terms as $child_term){\n echo '<li> -- '.$child_term->name.'</li>';\n }\n echo \"</ul><br>\";\n }\n echo \"</ul>\"; \n } \n</code></pre>\n\n<p>This should display the name of parent category and all its child category after.</p>\n"
},
{
"answer_id": 286656,
"author": "Sourav Kundu",
"author_id": 120713,
"author_profile": "https://wordpress.stackexchange.com/users/120713",
"pm_score": 0,
"selected": false,
"text": "<p>You Can Try This Code</p>\n\n<pre>\n$getterms=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ));\nforeach( $getterms as $parent_term ) \n{\n echo $parent_term->name;\n $getpchild=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );\n foreach( $getpchild as $child_term ) \n {\n echo $child_term->name;\n }\n\n}\n</pre>\n"
},
{
"answer_id": 286668,
"author": "Lovin Nagi",
"author_id": 102970,
"author_profile": "https://wordpress.stackexchange.com/users/102970",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach($listCatTerms as $listCatTerm) {\n\n //parent categories\n echo '<li>'.$listCatTerm->name.'</li>';\n\n //get childern term ID \n $term_children = get_term_children( $listCatTerm->term_id, 'listing-category' );\n foreach ( $term_children as $child ) { \n //Get all Term data from database by Term field and data.\n $term = get_term_by( 'id', $child, 'listing-category' );\n //childern categories of its parent category\n echo '<li class=\"lp-wrap-cats\">'.$term->name.'</li>';\n }\n }\n echo \"</ul>\"; \n }\n</code></pre>\n"
}
] |
2017/11/22
|
[
"https://wordpress.stackexchange.com/questions/286660",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128998/"
] |
I crated a footer.php and a corresponding customFooter.php. It looked great until I added header.php and customHeader.css. Now the 2 custom css files are overlaping. For example: some of the `<img>` are not aligned properly, due to the alignment of the pther css file.
Is it possible to restrict certain css file only to a specific pphp file??
|
Here you go:
```
$args = array(
'post_type' => 'listing',
'order' => 'ASC',
'hide_empty' => false,
'parent' => 0,
);
$listCatTerms = get_terms( 'listing-category',$args);
if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
echo "<ul>";
foreach ( $listCatTerms as $term ) {
echo '<li>'.$term->name.'</li>';
$child_terms = get_categories( array(
'parent' => $term->term_id,
'hide_empty' => 0 ));
//var_dump($child_terms);
echo "<ul>";
foreach($child_terms as $child_term){
echo '<li> -- '.$child_term->name.'</li>';
}
echo "</ul><br>";
}
echo "</ul>";
}
```
This should display the name of parent category and all its child category after.
|
286,706 |
<p>I have spent the last hour googling and trying different methods but nothing works the way I want it to.</p>
<p>Within the loop of the posts, I need to get the permalink of the main page. </p>
<h2>Example</h2>
<p>You have a portfolio custom post type and then a page where you show all of your work <code>archive-portfolio.php</code>, I need to get the link to the main portfolio page/archive-page within the loop.</p>
<p>The latest I have tried is getting the ID of the page outside of the loop and setting it to a variable then calling it later on in the loop.</p>
<pre><code>$page_id = get_the_ID();
</code></pre>
<p>but because i am using an <code>archive-{post-type}.php</code> it is not working, correctly. </p>
<p>Is there another solution other than changing over to <code>page-{template</code>} and implementing that method?</p>
|
[
{
"answer_id": 286641,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 1,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach ( $listCatTerms as $term ) {\n echo '<li>'.$term->name.'</li>';\n $child_terms = get_categories( array(\n 'parent' => $term->term_id,\n 'hide_empty' => 0 ));\n //var_dump($child_terms);\n echo \"<ul>\";\n foreach($child_terms as $child_term){\n echo '<li> -- '.$child_term->name.'</li>';\n }\n echo \"</ul><br>\";\n }\n echo \"</ul>\"; \n } \n</code></pre>\n\n<p>This should display the name of parent category and all its child category after.</p>\n"
},
{
"answer_id": 286656,
"author": "Sourav Kundu",
"author_id": 120713,
"author_profile": "https://wordpress.stackexchange.com/users/120713",
"pm_score": 0,
"selected": false,
"text": "<p>You Can Try This Code</p>\n\n<pre>\n$getterms=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ));\nforeach( $getterms as $parent_term ) \n{\n echo $parent_term->name;\n $getpchild=get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );\n foreach( $getpchild as $child_term ) \n {\n echo $child_term->name;\n }\n\n}\n</pre>\n"
},
{
"answer_id": 286668,
"author": "Lovin Nagi",
"author_id": 102970,
"author_profile": "https://wordpress.stackexchange.com/users/102970",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$args = array(\n 'post_type' => 'listing',\n 'order' => 'ASC',\n 'hide_empty' => false,\n 'parent' => 0,\n );\n\n $listCatTerms = get_terms( 'listing-category',$args);\n\n if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){ \n echo \"<ul>\"; \n foreach($listCatTerms as $listCatTerm) {\n\n //parent categories\n echo '<li>'.$listCatTerm->name.'</li>';\n\n //get childern term ID \n $term_children = get_term_children( $listCatTerm->term_id, 'listing-category' );\n foreach ( $term_children as $child ) { \n //Get all Term data from database by Term field and data.\n $term = get_term_by( 'id', $child, 'listing-category' );\n //childern categories of its parent category\n echo '<li class=\"lp-wrap-cats\">'.$term->name.'</li>';\n }\n }\n echo \"</ul>\"; \n }\n</code></pre>\n"
}
] |
2017/11/22
|
[
"https://wordpress.stackexchange.com/questions/286706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130535/"
] |
I have spent the last hour googling and trying different methods but nothing works the way I want it to.
Within the loop of the posts, I need to get the permalink of the main page.
Example
-------
You have a portfolio custom post type and then a page where you show all of your work `archive-portfolio.php`, I need to get the link to the main portfolio page/archive-page within the loop.
The latest I have tried is getting the ID of the page outside of the loop and setting it to a variable then calling it later on in the loop.
```
$page_id = get_the_ID();
```
but because i am using an `archive-{post-type}.php` it is not working, correctly.
Is there another solution other than changing over to `page-{template`} and implementing that method?
|
Here you go:
```
$args = array(
'post_type' => 'listing',
'order' => 'ASC',
'hide_empty' => false,
'parent' => 0,
);
$listCatTerms = get_terms( 'listing-category',$args);
if ( ! empty( $listCatTerms ) && ! is_wp_error( $listCatTerms ) ){
echo "<ul>";
foreach ( $listCatTerms as $term ) {
echo '<li>'.$term->name.'</li>';
$child_terms = get_categories( array(
'parent' => $term->term_id,
'hide_empty' => 0 ));
//var_dump($child_terms);
echo "<ul>";
foreach($child_terms as $child_term){
echo '<li> -- '.$child_term->name.'</li>';
}
echo "</ul><br>";
}
echo "</ul>";
}
```
This should display the name of parent category and all its child category after.
|
286,726 |
<p>I have set the "shop" page as my front page and I want to remove the default woocommerce title from the home page of the site.
I have emptied the title but I still get an empty tag like this on the home page:</p>
<pre><code><h1 class="woocommerce-products-header__title page-title"></h1>
</code></pre>
<p>This creates an empty area above the content which is annoying. I have tried the following solutions and they work BUT <strong>the title page for category pages would be removed too</strong>. I want the title only at the home page be removed.</p>
<ol>
<li><p>First solution: I added the following code to my style:</p>
<pre><code>.woocommerce-page .page-title {
display: none;
}
</code></pre></li>
<li><p>Added the following to function.php</p>
<pre><code>add_filter('woocommerce_show_page_title', '__return_false');
</code></pre></li>
</ol>
<p>I repeat, these solutions do what they are supposed to but I want the page-title for categories remain and only the title for the home page be removed.</p>
|
[
{
"answer_id": 286728,
"author": "meDeepakJain",
"author_id": 85593,
"author_profile": "https://wordpress.stackexchange.com/users/85593",
"pm_score": 1,
"selected": false,
"text": "<p>Few alternate ways to do so:</p>\n\n<ol>\n<li>Remove title code from your theme's home.php</li>\n<li>Create a template for products page</li>\n<li>For homepage, if you are using frontpage.php then it is quite easy to remove it from there. Else, you can use the last point mentioned below</li>\n<li>Go to your page.php and write a simple conditional statement to check if it is a homepage or not. A reference of this conditional statement from WP codex is here</li>\n</ol>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_home/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_home/</a> </p>\n"
},
{
"answer_id": 286729,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 2,
"selected": true,
"text": "<p>you can overwrite woocommerce template of <strong>\"archive-product.php\"</strong> into your current theme and replace with this code.</p>\n\n<pre><code><?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>\n\n <?php if(!is_shop()) { ?>\n <h1 class=\"page-title\"><?php woocommerce_page_title(); ?></h1>\n <?php } ?>\n<?php endif; ?>\n</code></pre>\n\n<p>For reference <a href=\"https://docs.woocommerce.com/document/conditional-tags/\" rel=\"nofollow noreferrer\">conditional tag of woocommerce</a> </p>\n\n<p><strong>OR</strong></p>\n\n<pre><code><?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>\n\n <?php if(is_product_category()) { ?>\n <h1 class=\"page-title\"><?php woocommerce_page_title(); ?></h1>\n <?php } ?>\n <?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 286731,
"author": "Niket Joshi",
"author_id": 122094,
"author_profile": "https://wordpress.stackexchange.com/users/122094",
"pm_score": 2,
"selected": false,
"text": "<p>Hello you can do this thing and i hope this work for you also</p>\n\n<pre><code> <?php\n if (!is_shop()) {\n if ( apply_filters( 'woocommerce_show_page_title', true ) ) { ?>\n <h1 class=\"page-title\"><?php woocommerce_page_title(); ?></h1>\n <?php }else{ ?>\n <h1 class=\"page-title\"><?php echo ''; ?>\n }\n } ?>\n</code></pre>\n\n<p>For More <a href=\"http://templatetoaster.com/forum/2937/how-to-remove-page-titles-on-woocommerce-pages\" rel=\"nofollow noreferrer\">Prefer this link</a></p>\n"
},
{
"answer_id": 318935,
"author": "Ryszard Jędraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of hacking templates, you can put this in functions.php of your child theme:</p>\n\n<pre><code>add_filter( 'woocommerce_show_page_title', 'not_a_shop_page' );\nfunction not_a_shop_page() {\n return boolval(!is_shop());\n}\n</code></pre>\n"
},
{
"answer_id": 371261,
"author": "Mr. Baka",
"author_id": 191793,
"author_profile": "https://wordpress.stackexchange.com/users/191793",
"pm_score": 1,
"selected": false,
"text": "<p>To remove the title only from the product page you need to add this code to your css styles</p>\n<pre><code>.product-template-default .woocommerce-products-header {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 409533,
"author": "skelenin",
"author_id": 225827,
"author_profile": "https://wordpress.stackexchange.com/users/225827",
"pm_score": 0,
"selected": false,
"text": "<p>I just did this for my website, but in a more round about way.</p>\n<ol>\n<li>I edited my archive-product.php file in the theme file editor and changed:</li>\n</ol>\n<p><code><h1 class="entry-title"><?php woocommerce_page_title(); ?></h1></code></p>\n<p>To:</p>\n<p><code><h6 class="entry-title"><?php woocommerce_page_title(); ?></h6></code></p>\n<ol start=\"2\">\n<li>I then edited the stylesheet page and added:</li>\n</ol>\n<p><code>h6 {display: none;}</code></p>\n<p>Obviously you shouldn't use this solution if you have h6 titles in your code, but for a simple solution, it does the trick.</p>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125637/"
] |
I have set the "shop" page as my front page and I want to remove the default woocommerce title from the home page of the site.
I have emptied the title but I still get an empty tag like this on the home page:
```
<h1 class="woocommerce-products-header__title page-title"></h1>
```
This creates an empty area above the content which is annoying. I have tried the following solutions and they work BUT **the title page for category pages would be removed too**. I want the title only at the home page be removed.
1. First solution: I added the following code to my style:
```
.woocommerce-page .page-title {
display: none;
}
```
2. Added the following to function.php
```
add_filter('woocommerce_show_page_title', '__return_false');
```
I repeat, these solutions do what they are supposed to but I want the page-title for categories remain and only the title for the home page be removed.
|
you can overwrite woocommerce template of **"archive-product.php"** into your current theme and replace with this code.
```
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<?php if(!is_shop()) { ?>
<h1 class="page-title"><?php woocommerce_page_title(); ?></h1>
<?php } ?>
<?php endif; ?>
```
For reference [conditional tag of woocommerce](https://docs.woocommerce.com/document/conditional-tags/)
**OR**
```
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<?php if(is_product_category()) { ?>
<h1 class="page-title"><?php woocommerce_page_title(); ?></h1>
<?php } ?>
<?php endif; ?>
```
|
286,746 |
<p>I have about 100 blog posts and I've been successfully creating 'Page Templates' with ease - and when I create a page I can select the Page Template from the 'Page Attributes' which is all very nice and easy.</p>
<p>I thought the same would be possible for posts...</p>
<p>So I created a post template and saved it as 'single-template-1.php'</p>
<p>Having uploaded the Post Template I notice that there 'Post Attributes' dropdown isn't there so I cant select that template.</p>
<p>Any idea what I could do to fix that?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 286747,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 3,
"selected": false,
"text": "<p>You have to add the following lines at the top of your post template file: </p>\n\n<pre><code><?php\n/*\n * Template Name: Featured Article\n * Template Post Type: post, page, product\n */\n\n get_header(); ?>\n</code></pre>\n\n<p>Of course replace \"Featured Article\" with your desired template name and the list of post types with the post types you want to use the template for.</p>\n"
},
{
"answer_id": 363992,
"author": "YMG",
"author_id": 121857,
"author_profile": "https://wordpress.stackexchange.com/users/121857",
"pm_score": 0,
"selected": false,
"text": "<p>If it not works, try to delete * before words</p>\n\n<p>like that</p>\n\n<pre><code><?php\n/*\nTemplate Name: Featured Article\nTemplate Post Type: post, page, product\n*/\n\n get_header(); ?>\n</code></pre>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286746",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] |
I have about 100 blog posts and I've been successfully creating 'Page Templates' with ease - and when I create a page I can select the Page Template from the 'Page Attributes' which is all very nice and easy.
I thought the same would be possible for posts...
So I created a post template and saved it as 'single-template-1.php'
Having uploaded the Post Template I notice that there 'Post Attributes' dropdown isn't there so I cant select that template.
Any idea what I could do to fix that?
Thanks!
|
You have to add the following lines at the top of your post template file:
```
<?php
/*
* Template Name: Featured Article
* Template Post Type: post, page, product
*/
get_header(); ?>
```
Of course replace "Featured Article" with your desired template name and the list of post types with the post types you want to use the template for.
|
286,748 |
<p>Is it possible that Tag Cloud Widget will show only tags by category?</p>
<p>If a single post is from <code>sports</code> category, then the Tag Cloud Widget will only show tags about sports.</p>
|
[
{
"answer_id": 286747,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 3,
"selected": false,
"text": "<p>You have to add the following lines at the top of your post template file: </p>\n\n<pre><code><?php\n/*\n * Template Name: Featured Article\n * Template Post Type: post, page, product\n */\n\n get_header(); ?>\n</code></pre>\n\n<p>Of course replace \"Featured Article\" with your desired template name and the list of post types with the post types you want to use the template for.</p>\n"
},
{
"answer_id": 363992,
"author": "YMG",
"author_id": 121857,
"author_profile": "https://wordpress.stackexchange.com/users/121857",
"pm_score": 0,
"selected": false,
"text": "<p>If it not works, try to delete * before words</p>\n\n<p>like that</p>\n\n<pre><code><?php\n/*\nTemplate Name: Featured Article\nTemplate Post Type: post, page, product\n*/\n\n get_header(); ?>\n</code></pre>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286748",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128147/"
] |
Is it possible that Tag Cloud Widget will show only tags by category?
If a single post is from `sports` category, then the Tag Cloud Widget will only show tags about sports.
|
You have to add the following lines at the top of your post template file:
```
<?php
/*
* Template Name: Featured Article
* Template Post Type: post, page, product
*/
get_header(); ?>
```
Of course replace "Featured Article" with your desired template name and the list of post types with the post types you want to use the template for.
|
286,759 |
<p>I'd like to query the database directly, and determine which plugins are enabled.</p>
<p>How can I do this?</p>
|
[
{
"answer_id": 286760,
"author": "Piyush Rawat",
"author_id": 73600,
"author_profile": "https://wordpress.stackexchange.com/users/73600",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>get_options('active_plugins')</code> to retrieve all active plugins.</p>\n\n<p>For checking against one plugin active or not you can use it like this :</p>\n\n<pre><code>if (in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) )) { \n //Woocommerce Active\n}\nelse{\n //Woocommerce Deactive\n}\n</code></pre>\n"
},
{
"answer_id": 286761,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it like this:</p>\n\n<h2>SQL</h2>\n\n<pre><code>SELECT * FROM wp_options WHERE option_name = 'active_plugins';\n</code></pre>\n\n<p>But for better approach will be the WordPress way:</p>\n\n<h2>Wordpress</h2>\n\n<pre><code>if ( ! function_exists( 'get_plugins' ) ) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n}\n\n$active_plugins = get_option('active_plugins');\n$all_plugins = get_plugins();\n$activated_plugins = array();\n\nforeach ($active_plugins as $plugin){ \n if(isset($all_plugins[$plugin])){\n array_push($activated_plugins, $all_plugins[$plugin]);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 286762,
"author": "Chris Stryczynski",
"author_id": 65429,
"author_profile": "https://wordpress.stackexchange.com/users/65429",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a solution that outputs the values in a human readable format:</p>\n\n<pre><code>mysql -h 127.0.0.1 -u wordpress -p wordpress -ss --raw -N -e 'SELECT option_value FROM wp_options WHERE option_name=\"active_plugins\"' | php -r \"var_dump(unserialize(stream_get_contents(STDIN)));\"\n</code></pre>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65429/"
] |
I'd like to query the database directly, and determine which plugins are enabled.
How can I do this?
|
You can do it like this:
SQL
---
```
SELECT * FROM wp_options WHERE option_name = 'active_plugins';
```
But for better approach will be the WordPress way:
Wordpress
---------
```
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$active_plugins = get_option('active_plugins');
$all_plugins = get_plugins();
$activated_plugins = array();
foreach ($active_plugins as $plugin){
if(isset($all_plugins[$plugin])){
array_push($activated_plugins, $all_plugins[$plugin]);
}
}
```
|
286,764 |
<p>I use WooCommerce REST API for updating/creating/deleting products.
When I try to delete a product using <code>$woocommerce->post('products/batch')</code>, an image connected with a product is not deleting from the DB and filesystem. It takes up unnecessary space on the server. </p>
<p>What is the best way to resolve this problem?</p>
|
[
{
"answer_id": 286760,
"author": "Piyush Rawat",
"author_id": 73600,
"author_profile": "https://wordpress.stackexchange.com/users/73600",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>get_options('active_plugins')</code> to retrieve all active plugins.</p>\n\n<p>For checking against one plugin active or not you can use it like this :</p>\n\n<pre><code>if (in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) )) { \n //Woocommerce Active\n}\nelse{\n //Woocommerce Deactive\n}\n</code></pre>\n"
},
{
"answer_id": 286761,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 3,
"selected": false,
"text": "<p>You can do it like this:</p>\n\n<h2>SQL</h2>\n\n<pre><code>SELECT * FROM wp_options WHERE option_name = 'active_plugins';\n</code></pre>\n\n<p>But for better approach will be the WordPress way:</p>\n\n<h2>Wordpress</h2>\n\n<pre><code>if ( ! function_exists( 'get_plugins' ) ) {\n require_once ABSPATH . 'wp-admin/includes/plugin.php';\n}\n\n$active_plugins = get_option('active_plugins');\n$all_plugins = get_plugins();\n$activated_plugins = array();\n\nforeach ($active_plugins as $plugin){ \n if(isset($all_plugins[$plugin])){\n array_push($activated_plugins, $all_plugins[$plugin]);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 286762,
"author": "Chris Stryczynski",
"author_id": 65429,
"author_profile": "https://wordpress.stackexchange.com/users/65429",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a solution that outputs the values in a human readable format:</p>\n\n<pre><code>mysql -h 127.0.0.1 -u wordpress -p wordpress -ss --raw -N -e 'SELECT option_value FROM wp_options WHERE option_name=\"active_plugins\"' | php -r \"var_dump(unserialize(stream_get_contents(STDIN)));\"\n</code></pre>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131997/"
] |
I use WooCommerce REST API for updating/creating/deleting products.
When I try to delete a product using `$woocommerce->post('products/batch')`, an image connected with a product is not deleting from the DB and filesystem. It takes up unnecessary space on the server.
What is the best way to resolve this problem?
|
You can do it like this:
SQL
---
```
SELECT * FROM wp_options WHERE option_name = 'active_plugins';
```
But for better approach will be the WordPress way:
Wordpress
---------
```
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$active_plugins = get_option('active_plugins');
$all_plugins = get_plugins();
$activated_plugins = array();
foreach ($active_plugins as $plugin){
if(isset($all_plugins[$plugin])){
array_push($activated_plugins, $all_plugins[$plugin]);
}
}
```
|
286,788 |
<p>Is there a way to update plugins, themes, and core, all in one row, instead 3 rows, in WPCLI?</p>
<p>This is the current code I use in the <code>crontab</code> and that I'd like to improve:</p>
<pre><code>0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
</code></pre>
|
[
{
"answer_id": 286790,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>I'd do something like this:</p>\n\n<pre><code>0 0 * * * for dir in /var/www/html/*/; do cd \"$dir\" && \\\n( \\\n /usr/local/bin/wp core update --allow-root && \\\n /usr/local/bin/wp plugin update --all --allow-root && \\\n /usr/local/bin/wp theme update --all --allow-root \\\n); \\\ndone\n</code></pre>\n\n<p><code>\\</code> used to break lines up for readability; this should probably be a single line in your crontab, like so:</p>\n\n<pre><code>0 0 * * * for dir in /var/www/html/*/; do cd \"$dir\" && ( /usr/local/bin/wp core update --allow-root && /usr/local/bin/wp plugin update --all --allow-root && /usr/local/bin/wp theme update --all --allow-root ); done\n</code></pre>\n\n<p>I haven't tested this. However, I regularly do this from the command line (ie, not in crontab).</p>\n"
},
{
"answer_id": 286791,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>Run a script instead:</p>\n\n<pre><code>0 0 * * * for dir in /var/www/html/*/; do cd \"$dir\" && ./updatewp.sh; done\n</code></pre>\n\n<p>In <code>updatewp.sh</code>:</p>\n\n<pre><code>wp core update --all --allow-root\nwp plugin update --all --allow-root\nwp theme update --all --allow-root\n</code></pre>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286788",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131001/"
] |
Is there a way to update plugins, themes, and core, all in one row, instead 3 rows, in WPCLI?
This is the current code I use in the `crontab` and that I'd like to improve:
```
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
```
|
Run a script instead:
```
0 0 * * * for dir in /var/www/html/*/; do cd "$dir" && ./updatewp.sh; done
```
In `updatewp.sh`:
```
wp core update --all --allow-root
wp plugin update --all --allow-root
wp theme update --all --allow-root
```
|
286,805 |
<p>I've created a product with variations but they are not linked at the back end and won't show up on the product page unless i manually set them<a href="https://i.stack.imgur.com/Q5If8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5If8.jpg" alt="enter image description here"></a></p>
<pre><code>$data = [
'title'=> 'ship your idea5',
'type' => 'variable',
'description' => 'Trying it out for real',
'short_description' => 'Pellentesque habitant.',
'categories' => [
[
'name' => 'Movies',
'slug' => 'movies'
],
[
'name' => 'Romance',
'slug' => 'romance'
]
],
'images' => [
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_4_front.jpg',
'position' => 0
]
],
'attributes' => [
[
'name' => 'Color',
'position' => 0,
'visible' => true,
'variation' => true,
'options' => [
'Black',
'Green'
]
],
[
'name' => 'Size',
'position' => 0,
'visible' => true,
'variation' => true,
'options' => [
'S',
'M'
]
]
],
'default_attributes' => [
[
'name' => 'Color',
'option' => 'Black'
],
[
'name' => 'Size',
'option' => 'S'
]
],
'variations' => array(
array( 'regular_price' => '29.98',
'attributes' => array(
array( 'name'=>'Color', 'options'=>'Black' )
)
),
array( 'regular_price' => '29.98',
'attributes' => array(
array( 'name'=>'color', 'options'=>'Green' )
)
)
)
];
$client->products->create($data);
</code></pre>
<p>any help is highly appreciated </p>
|
[
{
"answer_id": 322000,
"author": "Ramuchit Kumar",
"author_id": 156014,
"author_profile": "https://wordpress.stackexchange.com/users/156014",
"pm_score": 1,
"selected": false,
"text": "<p>you have to create another request for variation.</p>\n\n<pre><code>$variation_data = [\n 'regular_price' => '15.00',\n 'image' => [\n 'src' => 'https://shop.local/path/to/image_size_l.jpg',\n ],\n 'attributes' => [\n [\n 'id' => 5,\n 'option' => 'L',\n ],\n ],\n];\n\n$this->woocommerce->post( \"products/$product->id/variations\", $variation_data );\n</code></pre>\n"
},
{
"answer_id": 357846,
"author": "Maulik Makwana",
"author_id": 182122,
"author_profile": "https://wordpress.stackexchange.com/users/182122",
"pm_score": 0,
"selected": false,
"text": "<p>You can use variations/batch and used your existing product attributes\n/wp-json/wc/v3/products//variations/batch\n<a href=\"https://i.stack.imgur.com/0q9Cb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0q9Cb.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2017/11/23
|
[
"https://wordpress.stackexchange.com/questions/286805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119733/"
] |
I've created a product with variations but they are not linked at the back end and won't show up on the product page unless i manually set them[](https://i.stack.imgur.com/Q5If8.jpg)
```
$data = [
'title'=> 'ship your idea5',
'type' => 'variable',
'description' => 'Trying it out for real',
'short_description' => 'Pellentesque habitant.',
'categories' => [
[
'name' => 'Movies',
'slug' => 'movies'
],
[
'name' => 'Romance',
'slug' => 'romance'
]
],
'images' => [
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_4_front.jpg',
'position' => 0
]
],
'attributes' => [
[
'name' => 'Color',
'position' => 0,
'visible' => true,
'variation' => true,
'options' => [
'Black',
'Green'
]
],
[
'name' => 'Size',
'position' => 0,
'visible' => true,
'variation' => true,
'options' => [
'S',
'M'
]
]
],
'default_attributes' => [
[
'name' => 'Color',
'option' => 'Black'
],
[
'name' => 'Size',
'option' => 'S'
]
],
'variations' => array(
array( 'regular_price' => '29.98',
'attributes' => array(
array( 'name'=>'Color', 'options'=>'Black' )
)
),
array( 'regular_price' => '29.98',
'attributes' => array(
array( 'name'=>'color', 'options'=>'Green' )
)
)
)
];
$client->products->create($data);
```
any help is highly appreciated
|
you have to create another request for variation.
```
$variation_data = [
'regular_price' => '15.00',
'image' => [
'src' => 'https://shop.local/path/to/image_size_l.jpg',
],
'attributes' => [
[
'id' => 5,
'option' => 'L',
],
],
];
$this->woocommerce->post( "products/$product->id/variations", $variation_data );
```
|
286,823 |
<p>//The textarea is displayed when the if clause evaluates to false.
// What do I need to change?</p>
<pre><code><?php
if ( 1==2)
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
</code></pre>
|
[
{
"answer_id": 286825,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>You don't have a complete code there:</p>\n\n<pre><code><?php \nif ( 1==2): ?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\"\n</textarea>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 286831,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 2,
"selected": true,
"text": "<p>You may do it this way using open/close bracket <strong>{}</strong></p>\n\n<pre><code><?php \nif ( 1==2) { \n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>In general rules you need to enclose all the <code>if else</code> statement using php tag and the html outside it. You may also use echo.</p>\n\n<hr>\n\n<pre><code><?php if ( condition ) { ?>\n <!-- your html goes here -->\n<?php } else { ?>\n <!-- another html goes here -->\n<?php } ?>\n</code></pre>\n\n<p>Example with the use of echo (using ony one php tag to open/close the block)</p>\n\n<pre><code><?php if ( condition ) { \n echo \"<p>Some text content</p>\";\n } else { \n echo \"<p>Another text content</p>\";\n } ?>\n</code></pre>\n"
},
{
"answer_id": 286836,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may use this code to get your required output</p>\n\n<pre><code><?php \n\nif ( 1!=2) {\n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>So please check it and acknowledge me for the same</p>\n"
}
] |
2017/11/24
|
[
"https://wordpress.stackexchange.com/questions/286823",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129686/"
] |
//The textarea is displayed when the if clause evaluates to false.
// What do I need to change?
```
<?php
if ( 1==2)
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
```
|
You may do it this way using open/close bracket **{}**
```
<?php
if ( 1==2) {
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
<?php } ?>
```
In general rules you need to enclose all the `if else` statement using php tag and the html outside it. You may also use echo.
---
```
<?php if ( condition ) { ?>
<!-- your html goes here -->
<?php } else { ?>
<!-- another html goes here -->
<?php } ?>
```
Example with the use of echo (using ony one php tag to open/close the block)
```
<?php if ( condition ) {
echo "<p>Some text content</p>";
} else {
echo "<p>Another text content</p>";
} ?>
```
|
286,879 |
<p>Is it possible to pass variable to <code>get_search_form()</code>? </p>
<p>I'm using it in two places: one in header and on the search page in the content. The latter must have additional class, e.g. <code>search--full</code>. I've tried to use <code>is_search()</code> but while it works well on other pages, on search page both forms have <code>search--full</code> class. </p>
|
[
{
"answer_id": 286825,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>You don't have a complete code there:</p>\n\n<pre><code><?php \nif ( 1==2): ?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\"\n</textarea>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 286831,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 2,
"selected": true,
"text": "<p>You may do it this way using open/close bracket <strong>{}</strong></p>\n\n<pre><code><?php \nif ( 1==2) { \n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>In general rules you need to enclose all the <code>if else</code> statement using php tag and the html outside it. You may also use echo.</p>\n\n<hr>\n\n<pre><code><?php if ( condition ) { ?>\n <!-- your html goes here -->\n<?php } else { ?>\n <!-- another html goes here -->\n<?php } ?>\n</code></pre>\n\n<p>Example with the use of echo (using ony one php tag to open/close the block)</p>\n\n<pre><code><?php if ( condition ) { \n echo \"<p>Some text content</p>\";\n } else { \n echo \"<p>Another text content</p>\";\n } ?>\n</code></pre>\n"
},
{
"answer_id": 286836,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may use this code to get your required output</p>\n\n<pre><code><?php \n\nif ( 1!=2) {\n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>So please check it and acknowledge me for the same</p>\n"
}
] |
2017/11/24
|
[
"https://wordpress.stackexchange.com/questions/286879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] |
Is it possible to pass variable to `get_search_form()`?
I'm using it in two places: one in header and on the search page in the content. The latter must have additional class, e.g. `search--full`. I've tried to use `is_search()` but while it works well on other pages, on search page both forms have `search--full` class.
|
You may do it this way using open/close bracket **{}**
```
<?php
if ( 1==2) {
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
<?php } ?>
```
In general rules you need to enclose all the `if else` statement using php tag and the html outside it. You may also use echo.
---
```
<?php if ( condition ) { ?>
<!-- your html goes here -->
<?php } else { ?>
<!-- another html goes here -->
<?php } ?>
```
Example with the use of echo (using ony one php tag to open/close the block)
```
<?php if ( condition ) {
echo "<p>Some text content</p>";
} else {
echo "<p>Another text content</p>";
} ?>
```
|
286,890 |
<p>I'm trying to see if I am on a single page, this page is defined by:</p>
<ol>
<li>Is not the homepage for sure.</li>
<li>Doesn't have any posts for sure.</li>
</ol>
<p>Here's my code:</p>
<pre><code><?php if ( !is_home() && !have_posts() ) : ?>
<div class="single-page">
<?php endif; ?>
</code></pre>
<p>Added to <code>page.php</code>, but it doesn't seem to do anything. I know for a fact that simply adding html code to this file adds it to every single page.</p>
<p>What am I missing?</p>
|
[
{
"answer_id": 286825,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>You don't have a complete code there:</p>\n\n<pre><code><?php \nif ( 1==2): ?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\"\n</textarea>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 286831,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 2,
"selected": true,
"text": "<p>You may do it this way using open/close bracket <strong>{}</strong></p>\n\n<pre><code><?php \nif ( 1==2) { \n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>In general rules you need to enclose all the <code>if else</code> statement using php tag and the html outside it. You may also use echo.</p>\n\n<hr>\n\n<pre><code><?php if ( condition ) { ?>\n <!-- your html goes here -->\n<?php } else { ?>\n <!-- another html goes here -->\n<?php } ?>\n</code></pre>\n\n<p>Example with the use of echo (using ony one php tag to open/close the block)</p>\n\n<pre><code><?php if ( condition ) { \n echo \"<p>Some text content</p>\";\n } else { \n echo \"<p>Another text content</p>\";\n } ?>\n</code></pre>\n"
},
{
"answer_id": 286836,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may use this code to get your required output</p>\n\n<pre><code><?php \n\nif ( 1!=2) {\n?>\n<textarea>\n\"Add multiple lines of text here and watch the scrollbars grow.\">\n</textarea>\n<?php } ?>\n</code></pre>\n\n<p>So please check it and acknowledge me for the same</p>\n"
}
] |
2017/11/24
|
[
"https://wordpress.stackexchange.com/questions/286890",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130044/"
] |
I'm trying to see if I am on a single page, this page is defined by:
1. Is not the homepage for sure.
2. Doesn't have any posts for sure.
Here's my code:
```
<?php if ( !is_home() && !have_posts() ) : ?>
<div class="single-page">
<?php endif; ?>
```
Added to `page.php`, but it doesn't seem to do anything. I know for a fact that simply adding html code to this file adds it to every single page.
What am I missing?
|
You may do it this way using open/close bracket **{}**
```
<?php
if ( 1==2) {
?>
<textarea>
"Add multiple lines of text here and watch the scrollbars grow.">
</textarea>
<?php } ?>
```
In general rules you need to enclose all the `if else` statement using php tag and the html outside it. You may also use echo.
---
```
<?php if ( condition ) { ?>
<!-- your html goes here -->
<?php } else { ?>
<!-- another html goes here -->
<?php } ?>
```
Example with the use of echo (using ony one php tag to open/close the block)
```
<?php if ( condition ) {
echo "<p>Some text content</p>";
} else {
echo "<p>Another text content</p>";
} ?>
```
|
286,947 |
<p>I am building an application using WordPress Rest API.</p>
<p>I want to make simple calls to the API, such as just <strong><code>/wp-json/wp/v2/posts</code></strong> and let the backend have a systematic way how to handle this and serve <code>/wp-json/wp/v2/posts?per_page=7</code> under the hood instead.</p>
<p>Basically, how can I override the defaults for the Rest API responses without specifying them in the query string?</p>
<p>Again, I don't want to pass parameters in the query string. I need <em>simple query strings</em> and <em>standardized response</em>s.</p>
<p>This: <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/" rel="noreferrer">WordPress Docs - Modifying Responses</a> doesn't seem to cover my use case, it is to add fields and the like, which is not what I want to do. I'm looking for a way to hook into the request and alter it before returning a response.</p>
<p>So something a little before this hook: <a href="https://wordpress.stackexchange.com/questions/286307/rest-api-hook-when-post-is-requested">Rest API Hook When Post Is Requested</a> perhaps?</p>
<p>I gather that the above hook has already gotten ready to serve the response, I want to hook in <em>before that</em> to change the request headers.</p>
<p><strong>EDIT:</strong></p>
<p>The closest filter I have found is : <a href="https://developer.wordpress.org/reference/hooks/rest_request_from_url/" rel="noreferrer">this one</a> but it never seems to fire.</p>
<p>Furthermore, <a href="https://developer.wordpress.org/reference/hooks/rest_pre_dispatch/" rel="noreferrer">rest_pre_dispatch</a> is filtering the response, not the request.</p>
<p>Is there nothing like <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/request" rel="noreferrer">this</a> for the Rest API?</p>
<p>If so, how do I alter the response without slowing down my server, since it will fetch 10 posts by default before I chop it down to however many I actually want.</p>
|
[
{
"answer_id": 286975,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>To define default values, you can use the filter <code>rest_{$post_type}_collection_params</code> like that : </p>\n\n<pre><code>$post_type = \"post\";\n\nadd_filter(\"rest_{$post_type}_collection_params\", function ($query_params, $post_type) {\n\n $query_params[\"per_page\"][\"default\"] = 7;\n\n return $query_params;\n\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 375895,
"author": "Marko",
"author_id": 155071,
"author_profile": "https://wordpress.stackexchange.com/users/155071",
"pm_score": 2,
"selected": false,
"text": "<p>I think I found answer to your question, it is: <code>rest_{$this->post_type}_query </code> filter hook. With this hook you are able to directly edit internal WP_Query parameter.</p>\n<p>For example, if you'd like to internally sort Posts by <code>post_title</code> by default, then you'd have to write something like this:</p>\n<pre><code>function order_rest_post_by_post_title($args, $request) {\n $args['orderby'] = 'post_title';\n $args['order'] = 'DESC';\n\n return $args;\n}\nadd_filter('rest_post_query', 'order_rest_post_by_post_title', 10, 2);\n</code></pre>\n<p>For more info please follow <a href=\"https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/\" rel=\"nofollow noreferrer\">this</a> link.</p>\n"
}
] |
2017/11/26
|
[
"https://wordpress.stackexchange.com/questions/286947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77764/"
] |
I am building an application using WordPress Rest API.
I want to make simple calls to the API, such as just **`/wp-json/wp/v2/posts`** and let the backend have a systematic way how to handle this and serve `/wp-json/wp/v2/posts?per_page=7` under the hood instead.
Basically, how can I override the defaults for the Rest API responses without specifying them in the query string?
Again, I don't want to pass parameters in the query string. I need *simple query strings* and *standardized response*s.
This: [WordPress Docs - Modifying Responses](https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/) doesn't seem to cover my use case, it is to add fields and the like, which is not what I want to do. I'm looking for a way to hook into the request and alter it before returning a response.
So something a little before this hook: [Rest API Hook When Post Is Requested](https://wordpress.stackexchange.com/questions/286307/rest-api-hook-when-post-is-requested) perhaps?
I gather that the above hook has already gotten ready to serve the response, I want to hook in *before that* to change the request headers.
**EDIT:**
The closest filter I have found is : [this one](https://developer.wordpress.org/reference/hooks/rest_request_from_url/) but it never seems to fire.
Furthermore, [rest\_pre\_dispatch](https://developer.wordpress.org/reference/hooks/rest_pre_dispatch/) is filtering the response, not the request.
Is there nothing like [this](https://codex.wordpress.org/Plugin_API/Filter_Reference/request) for the Rest API?
If so, how do I alter the response without slowing down my server, since it will fetch 10 posts by default before I chop it down to however many I actually want.
|
I think I found answer to your question, it is: `rest_{$this->post_type}_query` filter hook. With this hook you are able to directly edit internal WP\_Query parameter.
For example, if you'd like to internally sort Posts by `post_title` by default, then you'd have to write something like this:
```
function order_rest_post_by_post_title($args, $request) {
$args['orderby'] = 'post_title';
$args['order'] = 'DESC';
return $args;
}
add_filter('rest_post_query', 'order_rest_post_by_post_title', 10, 2);
```
For more info please follow [this](https://developer.wordpress.org/reference/hooks/rest_this-post_type_query/) link.
|
286,955 |
<p>I have been working on a website using WordPress <a href="http://1stgoringheath.org.uk/" rel="nofollow noreferrer">http://1stgoringheath.org.uk/</a>, there are some pages that I didn't want to have the sidebar on, so I made a template and removed get_sidebar</p>
<p>Now I have just a blank area where the sidebar was, which I want to remove and allow the main content div fill the space.</p>
<p>The pictures below show the empty space</p>
<p><a href="https://i.stack.imgur.com/OzciX.png" rel="nofollow noreferrer">With Sidebar</a></p>
<p><a href="https://i.stack.imgur.com/TaPsj.png" rel="nofollow noreferrer">Without Sidebar</a></p>
<p>How can I fill the empty space where the sidebar was?</p>
<p>Thanks</p>
<p>Links to page.php and style.css are below
<a href="https://drive.google.com/file/d/1aVTgmO9uuJtbXlofDeS-bDSxsRawj2vd/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1aVTgmO9uuJtbXlofDeS-bDSxsRawj2vd/view?usp=sharing</a>
<a href="https://drive.google.com/file/d/1pV6OW5b0WlipUrs0fAWZAXBcLoR1_n14/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1pV6OW5b0WlipUrs0fAWZAXBcLoR1_n14/view?usp=sharing</a></p>
|
[
{
"answer_id": 286958,
"author": "Kins Okafor",
"author_id": 131906,
"author_profile": "https://wordpress.stackexchange.com/users/131906",
"pm_score": -1,
"selected": false,
"text": "<p>You can only remove the blank space by editing the custom css. First you need to be working on a Child's theme to ensure your theme's update do not reverse your changes. Then find the main class and set the width to 100%. A link to your website can help us give you further assistance</p>\n"
},
{
"answer_id": 286963,
"author": "Temani Afif",
"author_id": 128913,
"author_profile": "https://wordpress.stackexchange.com/users/128913",
"pm_score": 2,
"selected": true,
"text": "<p>You may add this code to your custom CSS :</p>\n\n<pre><code>.page-template-pageWithOutSidebar .entry-header, .page-template-pageWithOutSidebar .entry-content {\n padding-right: 0;\n}\n</code></pre>\n"
},
{
"answer_id": 342273,
"author": "user171398",
"author_id": 171398,
"author_profile": "https://wordpress.stackexchange.com/users/171398",
"pm_score": 0,
"selected": false,
"text": "<p>Within the parent container of the section whose left margin has to be removed add a \nclass= \"row \", and then in the child div element class = \"col - * - 12\"; , and then put \n* as md or sm or anything as required. </p>\n"
}
] |
2017/11/26
|
[
"https://wordpress.stackexchange.com/questions/286955",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132124/"
] |
I have been working on a website using WordPress <http://1stgoringheath.org.uk/>, there are some pages that I didn't want to have the sidebar on, so I made a template and removed get\_sidebar
Now I have just a blank area where the sidebar was, which I want to remove and allow the main content div fill the space.
The pictures below show the empty space
[With Sidebar](https://i.stack.imgur.com/OzciX.png)
[Without Sidebar](https://i.stack.imgur.com/TaPsj.png)
How can I fill the empty space where the sidebar was?
Thanks
Links to page.php and style.css are below
<https://drive.google.com/file/d/1aVTgmO9uuJtbXlofDeS-bDSxsRawj2vd/view?usp=sharing>
<https://drive.google.com/file/d/1pV6OW5b0WlipUrs0fAWZAXBcLoR1_n14/view?usp=sharing>
|
You may add this code to your custom CSS :
```
.page-template-pageWithOutSidebar .entry-header, .page-template-pageWithOutSidebar .entry-content {
padding-right: 0;
}
```
|
286,960 |
<p>I've been banging my head against the wall for last couple of days trying to exclude a category from an archive of easy digital downloads, which i am displaying in a custom widget, however i cannot hide a category called 'custom-project' no matter what i try.</p>
<p>This is the code i am trying to use, based on instructions from <a href="https://codex.wordpress.org/Class_Reference/WP_Query" rel="noreferrer">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>
<pre><code>$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'tax_query' => array(
array(
'taxonomy' => 'download_category',
'field' => 'slug',
'terms' => 'custom-project',
'include_children' => true,
'operator' => 'NOT_IN'
)
),
);
$get_latest_downloads = new WP_Query( $argsQuery );
$i=1;
while ( $get_latest_downloads->have_posts() ) : $get_latest_downloads->the_post();
//WIDGET BODY CODE
$i++;
endwhile;
</code></pre>
<p>I also tried using 'cat' instead of 'tax_query', but with no success as the category 'custom-project' is still displaying inside the loop of posts.</p>
<pre><code>$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'cat' => '-5',
);
$get_latest_downloads = new WP_Query( $argsQuery );
$i=1;
while ( $get_latest_downloads->have_posts() ) : $get_latest_downloads->the_post();
//WIDGET BODY CODE
$i++;
endwhile;
</code></pre>
<p>I am certain that slug name and category ID are correct. Any kind of help is greatly appreciated.</p>
|
[
{
"answer_id": 286961,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<h2>Issue 1</h2>\n\n<p>In your tax query, you should use <code>NOT IN</code> instead of <code>NOT_IN</code>. That's preventing your tax query from working ( Assuming that the other fields are correct ).</p>\n\n<h2>Issue 2</h2>\n\n<p>In your arguments for <code>WP_Query()</code>, you should use <code>category__not_in</code> instead of <code>cat</code>. So, change your code to:</p>\n\n<pre><code>$argsQuery = array(\n 'posts_per_page' => 3,\n 'post_type' => 'download',\n 'category__not_in' => 5 ,\n);\n</code></pre>\n"
},
{
"answer_id": 314451,
"author": "Joe",
"author_id": 90212,
"author_profile": "https://wordpress.stackexchange.com/users/90212",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>category__not_in (array) - use category id.</p>\n\n<pre>\n$argsQuery = array(\n 'posts_per_page' => 3,\n 'post_type' => 'download',\n 'category__not_in' => array( 5 ), // array, not a string\n);\n</pre>\n"
}
] |
2017/11/26
|
[
"https://wordpress.stackexchange.com/questions/286960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64807/"
] |
I've been banging my head against the wall for last couple of days trying to exclude a category from an archive of easy digital downloads, which i am displaying in a custom widget, however i cannot hide a category called 'custom-project' no matter what i try.
This is the code i am trying to use, based on instructions from <https://codex.wordpress.org/Class_Reference/WP_Query>
```
$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'tax_query' => array(
array(
'taxonomy' => 'download_category',
'field' => 'slug',
'terms' => 'custom-project',
'include_children' => true,
'operator' => 'NOT_IN'
)
),
);
$get_latest_downloads = new WP_Query( $argsQuery );
$i=1;
while ( $get_latest_downloads->have_posts() ) : $get_latest_downloads->the_post();
//WIDGET BODY CODE
$i++;
endwhile;
```
I also tried using 'cat' instead of 'tax\_query', but with no success as the category 'custom-project' is still displaying inside the loop of posts.
```
$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'cat' => '-5',
);
$get_latest_downloads = new WP_Query( $argsQuery );
$i=1;
while ( $get_latest_downloads->have_posts() ) : $get_latest_downloads->the_post();
//WIDGET BODY CODE
$i++;
endwhile;
```
I am certain that slug name and category ID are correct. Any kind of help is greatly appreciated.
|
Issue 1
-------
In your tax query, you should use `NOT IN` instead of `NOT_IN`. That's preventing your tax query from working ( Assuming that the other fields are correct ).
Issue 2
-------
In your arguments for `WP_Query()`, you should use `category__not_in` instead of `cat`. So, change your code to:
```
$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'category__not_in' => 5 ,
);
```
|
286,996 |
<p>I want to do some changes on WP for a friend but I don't want to do it live. So I was thinking of cloning the current WP to another directory on the same server and then do work on that version (www.myfriendswp.com -> www.myfriendswp.com/testing) and, when done, clone the changes back to main directory.</p>
<p>Is this possible or will there be some problems? Most tutorials and plugins are talking about cloning to a different server.</p>
|
[
{
"answer_id": 286961,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 4,
"selected": true,
"text": "<h2>Issue 1</h2>\n\n<p>In your tax query, you should use <code>NOT IN</code> instead of <code>NOT_IN</code>. That's preventing your tax query from working ( Assuming that the other fields are correct ).</p>\n\n<h2>Issue 2</h2>\n\n<p>In your arguments for <code>WP_Query()</code>, you should use <code>category__not_in</code> instead of <code>cat</code>. So, change your code to:</p>\n\n<pre><code>$argsQuery = array(\n 'posts_per_page' => 3,\n 'post_type' => 'download',\n 'category__not_in' => 5 ,\n);\n</code></pre>\n"
},
{
"answer_id": 314451,
"author": "Joe",
"author_id": 90212,
"author_profile": "https://wordpress.stackexchange.com/users/90212",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n\n<p>category__not_in (array) - use category id.</p>\n\n<pre>\n$argsQuery = array(\n 'posts_per_page' => 3,\n 'post_type' => 'download',\n 'category__not_in' => array( 5 ), // array, not a string\n);\n</pre>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/286996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105635/"
] |
I want to do some changes on WP for a friend but I don't want to do it live. So I was thinking of cloning the current WP to another directory on the same server and then do work on that version (www.myfriendswp.com -> www.myfriendswp.com/testing) and, when done, clone the changes back to main directory.
Is this possible or will there be some problems? Most tutorials and plugins are talking about cloning to a different server.
|
Issue 1
-------
In your tax query, you should use `NOT IN` instead of `NOT_IN`. That's preventing your tax query from working ( Assuming that the other fields are correct ).
Issue 2
-------
In your arguments for `WP_Query()`, you should use `category__not_in` instead of `cat`. So, change your code to:
```
$argsQuery = array(
'posts_per_page' => 3,
'post_type' => 'download',
'category__not_in' => 5 ,
);
```
|
287,015 |
<p>So far I've got the code below which achieves the effect I'm after, but it appends the title of only the current page to every page title on a page (including Next / Previous links which obviously have different titles), so I obviously need to retrieve the custom field value from these posts, but I'm struggling to achieve this. </p>
<pre><code> add_filter( 'the_title', 'post_title_append_alt_lang' );
function post_title_append_alt_lang( $title ) {
if( get_field( 'post_title_text_alt_language' ) && in_the_loop() ){
return $title.' <span class="chinese_trad" lang="'
. get_field(post_title_language) . '">'
. get_field(post_title_text_alt_language)
. '</span>';
}
return $title;
}
</code></pre>
<p>I know I need to tie the custom field retrieved to the post ID somehow, but I'm not sure of the best way to do this that will work for any posts that might appear on the page. </p>
<p>Any help would be greatly appreciated thanks! </p>
|
[
{
"answer_id": 287017,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to append something to EVERY post_title you have, you should:</p>\n\n<p>Make your loop with <code>WP Query</code>, <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">check Codex</a></p>\n\n<p>Then, use <code>get_the_ID</code>, to get the specific post ID, <a href=\"https://developer.wordpress.org/reference/functions/get_the_ID/\" rel=\"nofollow noreferrer\">check Codex</a></p>\n\n<p>Then, use the ID to get the ACF field from that specific post like <code>get_field('name-of-the-field)</code>, <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">check the documentation</a></p>\n\n<p>Don't forget to use <code>wp_reset_query()</code>, <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\">check the Codex</a></p>\n"
},
{
"answer_id": 287173,
"author": "andersonslookout",
"author_id": 132164,
"author_profile": "https://wordpress.stackexchange.com/users/132164",
"pm_score": -1,
"selected": false,
"text": "<p>OK, I found a solution in the end. Here's the function I went with:</p>\n\n<pre><code>function add_custom_field_after_title($title, $id) {\n\n if ( in_the_loop() ) {\n\n $custom_field = get_field( 'customfield', $id );\n\n if ( !empty($custom_field) ){\n $title .= $custom_field;\n }\n }\n\n return $title;\n }\n\nadd_filter('the_title','add_custom_field_after_title',10,2);\n</code></pre>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132164/"
] |
So far I've got the code below which achieves the effect I'm after, but it appends the title of only the current page to every page title on a page (including Next / Previous links which obviously have different titles), so I obviously need to retrieve the custom field value from these posts, but I'm struggling to achieve this.
```
add_filter( 'the_title', 'post_title_append_alt_lang' );
function post_title_append_alt_lang( $title ) {
if( get_field( 'post_title_text_alt_language' ) && in_the_loop() ){
return $title.' <span class="chinese_trad" lang="'
. get_field(post_title_language) . '">'
. get_field(post_title_text_alt_language)
. '</span>';
}
return $title;
}
```
I know I need to tie the custom field retrieved to the post ID somehow, but I'm not sure of the best way to do this that will work for any posts that might appear on the page.
Any help would be greatly appreciated thanks!
|
If you need to append something to EVERY post\_title you have, you should:
Make your loop with `WP Query`, [check Codex](https://codex.wordpress.org/Class_Reference/WP_Query)
Then, use `get_the_ID`, to get the specific post ID, [check Codex](https://developer.wordpress.org/reference/functions/get_the_ID/)
Then, use the ID to get the ACF field from that specific post like `get_field('name-of-the-field)`, [check the documentation](https://www.advancedcustomfields.com/resources/get_field/)
Don't forget to use `wp_reset_query()`, [check the Codex](https://codex.wordpress.org/Function_Reference/wp_reset_query)
|
287,033 |
<p>I want to make a rewrite-rule for latest posts <code>example.com/latest</code> via <code>rewrite_rules_array</code>-filterhook and display the posts with <code>archive.php</code>. </p>
<p>Usually this is what <code>example.com/index.php</code> does, I guess? But I use my themes <code>index.php</code> for a custom index page.</p>
<p><code>index.php?category_name=technik</code> successfully gets output from <code>archive.php</code>, but how can I get the output from <code>archive.php</code> with no additional filtering whatsoever?</p>
<pre><code>add_filter("rewrite_rules_array", function($rules) {
$newRules = array();
// works as expected
$newRules['fliegen/(.+)/?$'] = 'index.php?category_name=fliegen&filter=$matches[1]';
// output generated by themes index.php
$newRules['latest'] = 'index.php';
// also tried, but still output by themes index.php
$newRules['latest2'] = 'archive.php';
$newRules['latest3'] = 'wp-content/themes/mytheme/archive.php';
// Return merged rules
return array_merge($newRules, $rules);
});
</code></pre>
<p>I found a workaround, which is rather ugly– just list all categories ..</p>
<pre><code>index.php?category_name=technik,fliegen,foo,bar
</code></pre>
<p>But posts without category still won't be showed. Open for suggestions! Thanks.</p>
|
[
{
"answer_id": 287017,
"author": "Marcelo Henriques Cortez",
"author_id": 44437,
"author_profile": "https://wordpress.stackexchange.com/users/44437",
"pm_score": 0,
"selected": false,
"text": "<p>If you need to append something to EVERY post_title you have, you should:</p>\n\n<p>Make your loop with <code>WP Query</code>, <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">check Codex</a></p>\n\n<p>Then, use <code>get_the_ID</code>, to get the specific post ID, <a href=\"https://developer.wordpress.org/reference/functions/get_the_ID/\" rel=\"nofollow noreferrer\">check Codex</a></p>\n\n<p>Then, use the ID to get the ACF field from that specific post like <code>get_field('name-of-the-field)</code>, <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\">check the documentation</a></p>\n\n<p>Don't forget to use <code>wp_reset_query()</code>, <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\">check the Codex</a></p>\n"
},
{
"answer_id": 287173,
"author": "andersonslookout",
"author_id": 132164,
"author_profile": "https://wordpress.stackexchange.com/users/132164",
"pm_score": -1,
"selected": false,
"text": "<p>OK, I found a solution in the end. Here's the function I went with:</p>\n\n<pre><code>function add_custom_field_after_title($title, $id) {\n\n if ( in_the_loop() ) {\n\n $custom_field = get_field( 'customfield', $id );\n\n if ( !empty($custom_field) ){\n $title .= $custom_field;\n }\n }\n\n return $title;\n }\n\nadd_filter('the_title','add_custom_field_after_title',10,2);\n</code></pre>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287033",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102487/"
] |
I want to make a rewrite-rule for latest posts `example.com/latest` via `rewrite_rules_array`-filterhook and display the posts with `archive.php`.
Usually this is what `example.com/index.php` does, I guess? But I use my themes `index.php` for a custom index page.
`index.php?category_name=technik` successfully gets output from `archive.php`, but how can I get the output from `archive.php` with no additional filtering whatsoever?
```
add_filter("rewrite_rules_array", function($rules) {
$newRules = array();
// works as expected
$newRules['fliegen/(.+)/?$'] = 'index.php?category_name=fliegen&filter=$matches[1]';
// output generated by themes index.php
$newRules['latest'] = 'index.php';
// also tried, but still output by themes index.php
$newRules['latest2'] = 'archive.php';
$newRules['latest3'] = 'wp-content/themes/mytheme/archive.php';
// Return merged rules
return array_merge($newRules, $rules);
});
```
I found a workaround, which is rather ugly– just list all categories ..
```
index.php?category_name=technik,fliegen,foo,bar
```
But posts without category still won't be showed. Open for suggestions! Thanks.
|
If you need to append something to EVERY post\_title you have, you should:
Make your loop with `WP Query`, [check Codex](https://codex.wordpress.org/Class_Reference/WP_Query)
Then, use `get_the_ID`, to get the specific post ID, [check Codex](https://developer.wordpress.org/reference/functions/get_the_ID/)
Then, use the ID to get the ACF field from that specific post like `get_field('name-of-the-field)`, [check the documentation](https://www.advancedcustomfields.com/resources/get_field/)
Don't forget to use `wp_reset_query()`, [check the Codex](https://codex.wordpress.org/Function_Reference/wp_reset_query)
|
287,051 |
<p>i am new to plugin development in wordpress and i have have this simple test plugin that i am working on. The problem i am having is that the uninstall.php file does not appear to get trigger and as such the database entried i wish to remove remain after the plugin in uninstalled from the WordPress admin.</p>
<p><strong>Plugin code:</strong></p>
<pre><code>defined( 'ABSPATH' ) or die( 'Looks like you made a wrong turn there buddy' );
class TestPlugin
{
function __construct() {
add_action( 'init', array( $this, 'create_post_type' ) );
}
function activate() {
// generate a CPT in case 'init' fails
$this->create_post_type();
// flush rewrite rules
flush_rewrite_rules();
}
function deactivate() {
// flush rewrite rules
flush_rewrite_rules();
}
function uninstall() {
// delete cpt
// delete all the plugin data from the DB
}
function create_post_type() {
register_post_type( 'acme_product', array( 'public' => true, 'label' => 'Acme Product' ) );
}
}
if ( class_exists( 'TestPlugin' ) ) {
$newTest = new TestPlugin();
}
// Activation
register_activation_hook( __FILE__, array( $newTest, 'activate' ) );
// Deactivation
register_activation_hook( __FILE__, array( $newTest, 'deactivate' ) );
</code></pre>
<p><strong>Uninstall.php</strong></p>
<pre><code>/**
* Trigger this file on plugin uninstall
*
* @package TestPlugin
*/
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
die;
}
// Clear database stored data
//$acme_products = get_posts( array( 'post_type' => 'acme_product', 'numberposts' => -1 ) );
//
//foreach ( $acme_products as $acme_product) {
// wp_delete_post( $acme_product->ID, true );
//}
// Access the database via SQL
global $wpdb;
$wpdb->query( "DELETE FROM wp_posts WHERE post_type = 'acme_product'" );
$wpdb->query( "DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT id FROM wp_posts)" );
$wpdb->query( "DELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT id FROM wp_posts)" );
echo "UNINSTALL DAMMIT!!";
</code></pre>
<p><strong>UPDATE:</strong>
I have tested the SQL query just to make sure it worked in phpMyAdmin, and it works fine.</p>
<p>i.e <code>"DELETE FROM wp_posts WHERE post_type = 'acme_product'"</code></p>
|
[
{
"answer_id": 287044,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 0,
"selected": false,
"text": "<p>This should work: </p>\n\n<pre><code><img src=\"<?php echo do_shortcode('[my_shortcode]'); ?>\" />\n</code></pre>\n"
},
{
"answer_id": 287087,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot use Shortcodes in attributes since 4.2.3, for security reasons. See the <a href=\"https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/\" rel=\"nofollow noreferrer\">announcement</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Earlier today, we released WordPress 4.2.3, which includes a\n <strong>relatively large security fix that affects the Shortcode API</strong>. Due to\n the nature of the fix – as is often the case with security fixes – we\n were unable to alert plugin authors ahead of time, however we did make\n efforts to scan the plugin directory for plugins that may have been\n affected.</p>\n \n <p>With this change, every effort has been made to preserve all of the\n core features of the Shortcode API. That said, there are some new\n limitations that affect some rare uses of shortcodes.</p>\n \n <p>...</p>\n \n <p>In today’s release of WordPress 4.2.3, however, we’ve added some new\n limitations that affect some existing plugins. Take, for example, the\n following shortcode, which is no longer recognized:</p>\n \n <p><code><div style=\"background-image: url('[shortcode]');\"></code></p>\n \n <p><strong>The shortcode in the example above appears in a context that is no\n longer supported. Further, this use of a shortcode stretches the\n imagination for how the Shortcode API was intended to be used.</strong>\n Fortunately, there are some workarounds still available, so that site\n administrators are not overly restricted in their use of HTML.</p>\n</blockquote>\n\n<p>Read the full announcement for the workarounds.</p>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71390/"
] |
i am new to plugin development in wordpress and i have have this simple test plugin that i am working on. The problem i am having is that the uninstall.php file does not appear to get trigger and as such the database entried i wish to remove remain after the plugin in uninstalled from the WordPress admin.
**Plugin code:**
```
defined( 'ABSPATH' ) or die( 'Looks like you made a wrong turn there buddy' );
class TestPlugin
{
function __construct() {
add_action( 'init', array( $this, 'create_post_type' ) );
}
function activate() {
// generate a CPT in case 'init' fails
$this->create_post_type();
// flush rewrite rules
flush_rewrite_rules();
}
function deactivate() {
// flush rewrite rules
flush_rewrite_rules();
}
function uninstall() {
// delete cpt
// delete all the plugin data from the DB
}
function create_post_type() {
register_post_type( 'acme_product', array( 'public' => true, 'label' => 'Acme Product' ) );
}
}
if ( class_exists( 'TestPlugin' ) ) {
$newTest = new TestPlugin();
}
// Activation
register_activation_hook( __FILE__, array( $newTest, 'activate' ) );
// Deactivation
register_activation_hook( __FILE__, array( $newTest, 'deactivate' ) );
```
**Uninstall.php**
```
/**
* Trigger this file on plugin uninstall
*
* @package TestPlugin
*/
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
die;
}
// Clear database stored data
//$acme_products = get_posts( array( 'post_type' => 'acme_product', 'numberposts' => -1 ) );
//
//foreach ( $acme_products as $acme_product) {
// wp_delete_post( $acme_product->ID, true );
//}
// Access the database via SQL
global $wpdb;
$wpdb->query( "DELETE FROM wp_posts WHERE post_type = 'acme_product'" );
$wpdb->query( "DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT id FROM wp_posts)" );
$wpdb->query( "DELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT id FROM wp_posts)" );
echo "UNINSTALL DAMMIT!!";
```
**UPDATE:**
I have tested the SQL query just to make sure it worked in phpMyAdmin, and it works fine.
i.e `"DELETE FROM wp_posts WHERE post_type = 'acme_product'"`
|
You cannot use Shortcodes in attributes since 4.2.3, for security reasons. See the [announcement](https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/) (emphasis mine):
>
> Earlier today, we released WordPress 4.2.3, which includes a
> **relatively large security fix that affects the Shortcode API**. Due to
> the nature of the fix – as is often the case with security fixes – we
> were unable to alert plugin authors ahead of time, however we did make
> efforts to scan the plugin directory for plugins that may have been
> affected.
>
>
> With this change, every effort has been made to preserve all of the
> core features of the Shortcode API. That said, there are some new
> limitations that affect some rare uses of shortcodes.
>
>
> ...
>
>
> In today’s release of WordPress 4.2.3, however, we’ve added some new
> limitations that affect some existing plugins. Take, for example, the
> following shortcode, which is no longer recognized:
>
>
> `<div style="background-image: url('[shortcode]');">`
>
>
> **The shortcode in the example above appears in a context that is no
> longer supported. Further, this use of a shortcode stretches the
> imagination for how the Shortcode API was intended to be used.**
> Fortunately, there are some workarounds still available, so that site
> administrators are not overly restricted in their use of HTML.
>
>
>
Read the full announcement for the workarounds.
|
287,057 |
<p>I'm trying to adjust a function that checks if the site visitor is on a post type archive and returns a certain layout. I need it to also check to see if it is in certain categories (using regular WP categories - not custom taxonomies).</p>
<p>This is the original code that works.</p>
<pre><code>// ADD ARCHIVE LAYOUT FOR POSITION VIDEOS POST TYPE
function custom_filter_positionvids_layout( $layout_id ) {
if ( is_post_type_archive('position_video') )
return '58bef4ba370de';
return $layout_id;
}
add_filter( 'builder_filter_current_layout', 'custom_filter_positionvids_layout' );
</code></pre>
<p>Can I add some sort of && statement with category ID's so it will check if the page is displaying the post type archive and in a list of certain categories? This will help me give a different layout for protected member content.</p>
|
[
{
"answer_id": 287044,
"author": "grazdev",
"author_id": 129417,
"author_profile": "https://wordpress.stackexchange.com/users/129417",
"pm_score": 0,
"selected": false,
"text": "<p>This should work: </p>\n\n<pre><code><img src=\"<?php echo do_shortcode('[my_shortcode]'); ?>\" />\n</code></pre>\n"
},
{
"answer_id": 287087,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot use Shortcodes in attributes since 4.2.3, for security reasons. See the <a href=\"https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/\" rel=\"nofollow noreferrer\">announcement</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Earlier today, we released WordPress 4.2.3, which includes a\n <strong>relatively large security fix that affects the Shortcode API</strong>. Due to\n the nature of the fix – as is often the case with security fixes – we\n were unable to alert plugin authors ahead of time, however we did make\n efforts to scan the plugin directory for plugins that may have been\n affected.</p>\n \n <p>With this change, every effort has been made to preserve all of the\n core features of the Shortcode API. That said, there are some new\n limitations that affect some rare uses of shortcodes.</p>\n \n <p>...</p>\n \n <p>In today’s release of WordPress 4.2.3, however, we’ve added some new\n limitations that affect some existing plugins. Take, for example, the\n following shortcode, which is no longer recognized:</p>\n \n <p><code><div style=\"background-image: url('[shortcode]');\"></code></p>\n \n <p><strong>The shortcode in the example above appears in a context that is no\n longer supported. Further, this use of a shortcode stretches the\n imagination for how the Shortcode API was intended to be used.</strong>\n Fortunately, there are some workarounds still available, so that site\n administrators are not overly restricted in their use of HTML.</p>\n</blockquote>\n\n<p>Read the full announcement for the workarounds.</p>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132201/"
] |
I'm trying to adjust a function that checks if the site visitor is on a post type archive and returns a certain layout. I need it to also check to see if it is in certain categories (using regular WP categories - not custom taxonomies).
This is the original code that works.
```
// ADD ARCHIVE LAYOUT FOR POSITION VIDEOS POST TYPE
function custom_filter_positionvids_layout( $layout_id ) {
if ( is_post_type_archive('position_video') )
return '58bef4ba370de';
return $layout_id;
}
add_filter( 'builder_filter_current_layout', 'custom_filter_positionvids_layout' );
```
Can I add some sort of && statement with category ID's so it will check if the page is displaying the post type archive and in a list of certain categories? This will help me give a different layout for protected member content.
|
You cannot use Shortcodes in attributes since 4.2.3, for security reasons. See the [announcement](https://make.wordpress.org/core/2015/07/23/changes-to-the-shortcode-api/) (emphasis mine):
>
> Earlier today, we released WordPress 4.2.3, which includes a
> **relatively large security fix that affects the Shortcode API**. Due to
> the nature of the fix – as is often the case with security fixes – we
> were unable to alert plugin authors ahead of time, however we did make
> efforts to scan the plugin directory for plugins that may have been
> affected.
>
>
> With this change, every effort has been made to preserve all of the
> core features of the Shortcode API. That said, there are some new
> limitations that affect some rare uses of shortcodes.
>
>
> ...
>
>
> In today’s release of WordPress 4.2.3, however, we’ve added some new
> limitations that affect some existing plugins. Take, for example, the
> following shortcode, which is no longer recognized:
>
>
> `<div style="background-image: url('[shortcode]');">`
>
>
> **The shortcode in the example above appears in a context that is no
> longer supported. Further, this use of a shortcode stretches the
> imagination for how the Shortcode API was intended to be used.**
> Fortunately, there are some workarounds still available, so that site
> administrators are not overly restricted in their use of HTML.
>
>
>
Read the full announcement for the workarounds.
|
287,062 |
<p>I'm working on a new site that includes memberships, and I'd like the Page Title to be a different color on the membership page without changing on any of the other pages. I've seen code that helps change the home page title color (using .home) but none that use a different page. The page title is "A Voice That Cares" so even if I use this code, it doesn't change:</p>
<pre><code>.a-voice-that-cares .gk-logo-text.inverse > span {
color: blue!important;
}
</code></pre>
<p>or</p>
<pre><code>.a-voice-that-cares .h1 {
color: blue!important;
}
</code></pre>
<p>Any help/suggestions would be greatly appreciated! Thank you!</p>
|
[
{
"answer_id": 287071,
"author": "Patrice Poliquin",
"author_id": 32365,
"author_profile": "https://wordpress.stackexchange.com/users/32365",
"pm_score": 0,
"selected": false,
"text": "<p>Firstly, I would recommend you to create a custom template page (<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">WordPress templates documentation</a>).</p>\n\n<p><code><?php /* Template Name: Example Template */ ?></code></p>\n\n<p>On your new page, you can copy-paste the HTML code from <code>page.php</code> for example and do a quick work-arround.</p>\n\n<pre><code><?php\n\n/* Template Name: Membership */\n\nget_header(); \n\n?>\n\n<div id=\"primary\" class=\"site-content\">\n\n <div id=\"content\" role=\"main\">\n\n <?php while ( have_posts() ) : the_post(); ?>\n\n <h1 class=\"membership-title\"><?php the_title(); ?>\n\n <!-- Your content ... -->\n\n <?php endwhile; ?>\n\n </div>\n\n</div>\n\n<?php get_sidebar(); ?>\n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>And in your CSS, you would only have to create your class.</p>\n\n<pre><code>h1.membership-title {\n color: blue;\n}\n</code></pre>\n\n<p>After you saved and uploaded your files, return in your Admin panel and change the page attribute <code>parent</code> to the one you need.</p>\n\n<p>With this new template, all default pages will have the default style you have seted and the new page will have the new style. This style will only apply to the pages you have seted to <code>Membership</code>.</p>\n\n<p>Hope it was what you were looking for.</p>\n"
},
{
"answer_id": 287072,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 0,
"selected": false,
"text": "<p>Here's how I'd do it (probably in the active theme's <code>functions.php</code>, since you're trying to affect how a page looks):</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wpse_287062_add_style', 100 );\nfunction wpse_287062_add_style() {\n if ( is_page( 'a-voice-that-cares' ) ) {\n wp_add_inline_style( 'stylesheet-handle', 'h1 { color: blue !important; }' );\n }\n}\n</code></pre>\n\n<p>You'll need to figure out your theme's <code>stylesheet-handle</code>.</p>\n\n<p>For an example of how to do this, I'll use the current default theme, <strong>Twenty Seventeen</strong>. When I view the source of a WordPress-generated page that uses the Twenty Seventeen theme, I see the following line:</p>\n\n<pre><code><link rel='stylesheet' id='twentyseventeen-style-css' href='http://example.com/wp-content/themes/twentyseventeen/style.css?ver=4.9' type='text/css' media='all' />\n</code></pre>\n\n<p>The stylesheet handle is the <code>id</code>, minus the <code>-css</code> suffix. So in Twenty Seventeen's case, the <code>stylesheet-handle</code> in the code above should be replaced by <code>twentyseventeen-style</code>.</p>\n\n<h1>References</h1>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow noreferrer\"><code>is_page()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_style/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_style()</code></a></li>\n<li><a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code> hook</a></li>\n</ul>\n"
},
{
"answer_id": 287076,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using <code>body_class</code> and <code>post_class</code> correctly, you should have CSS classes you can match against that take the form <code>postid-0001</code> etc</p>\n\n<p>Next you need the CSS to change the <code>h1</code> colour</p>\n\n<p>Find the ID of your membership page, and use the CSS class in your CSS selector so it only matches on that page.</p>\n\n<p>e.g. <code>.postid-0001 h1 { color: red; }</code></p>\n\n<p>Ofcourse your membership title may not be a <code>h1</code> element, and at this point it's a pure CSS question. Use the customizer to put your CSS code in and hey presto, your title colour has changed</p>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287062",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132204/"
] |
I'm working on a new site that includes memberships, and I'd like the Page Title to be a different color on the membership page without changing on any of the other pages. I've seen code that helps change the home page title color (using .home) but none that use a different page. The page title is "A Voice That Cares" so even if I use this code, it doesn't change:
```
.a-voice-that-cares .gk-logo-text.inverse > span {
color: blue!important;
}
```
or
```
.a-voice-that-cares .h1 {
color: blue!important;
}
```
Any help/suggestions would be greatly appreciated! Thank you!
|
If you're using `body_class` and `post_class` correctly, you should have CSS classes you can match against that take the form `postid-0001` etc
Next you need the CSS to change the `h1` colour
Find the ID of your membership page, and use the CSS class in your CSS selector so it only matches on that page.
e.g. `.postid-0001 h1 { color: red; }`
Ofcourse your membership title may not be a `h1` element, and at this point it's a pure CSS question. Use the customizer to put your CSS code in and hey presto, your title colour has changed
|
287,078 |
<pre><code>Array (
[0] => Array ( [week-day] => tuesday [day-date] => 1511841600 [events_ids] => Array ( [0] => 83417 ) )
[1] => Array ( [week-day] => wednesday [day-date] => 1511913600 [events_ids] => Array ( [0] => 83417 ) )
[2] => Array ( [week-day] => thrusday [day-date] => 1512000000 [events_ids] => Array ( [0] => 83417 ) )
[3] => Array ( [week-day] => tuesday [day-date] => 1511830800 [events_ids] => Array ( [0] => 83411 ) )
)
</code></pre>
<p>How do I get the first value <code>tuesday</code> of key <code>week-day</code> and combine all <code>events_ids</code> of all tuesdays?</p>
|
[
{
"answer_id": 287080,
"author": "Andrew Herder",
"author_id": 81637,
"author_profile": "https://wordpress.stackexchange.com/users/81637",
"pm_score": 2,
"selected": true,
"text": "<p>This should get the desired result:</p>\n\n<pre><code>//Initial Array\n$events = array\n(\n array\n (\n 'week-day' => 'tuesday',\n 'day-date' => 1511841600,\n 'events_ids' => array( 83417 )\n ),\n array\n (\n 'week-day' => 'wednesday',\n 'day-date' => 1511913600,\n 'events_ids' => array( 83419, 12345 )\n ),\n array\n (\n 'week-day' => 'tuesday',\n 'day-date' => 1511830800,\n 'events_ids' => array( 83411 )\n )\n);\n\n//Array to fill\n$tuesday_event_ids = array();\n\nforeach($events as $event ):\n\n //if day is tuesday & we have event IDs\n if($event['week-day'] === 'tuesday' && count($event['events_ids'])):\n foreach($event['events_ids'] as $id):\n\n //Push to array if not already in it\n if(!in_array($id,$tuesday_event_ids))\n array_push($tuesday_event_ids, $id);\n\n endforeach;\n endif;\n\nendforeach;\n\n//should be: array(83417,83411)\nvar_dump($tuesday_event_ids);\n</code></pre>\n\n<p>side note: you may want to consider changing the array keys to either be all <code>-</code> based or all <code>_</code> based for sanity.</p>\n"
},
{
"answer_id": 287082,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 0,
"selected": false,
"text": "<p>This will copy first unique weekday to the new array and then if that weekday repeats it will just add the events IDs.</p>\n\n<pre><code>$events = [\n [\n 'week-day' => 'tuesday',\n 'day-date' => 1511841600,\n 'events_ids' => [83417]\n ],\n [\n 'week-day' => 'wednesday',\n 'day-date' => 1511913600,\n 'events_ids' => [83417]\n ],\n [\n 'week-day' => 'thrusday',\n 'day-date' => 1512000000,\n 'events_ids' => [83417]\n ],\n [\n 'week-day' => 'tuesday',\n 'day-date' => 1511830800,\n 'events_ids' => [83417]\n ]\n];\n\n$new_events = [];\n\nforeach ( $events as $event ) {\n if ( array_key_exists( $event['week-day'], $new_events ) ) {\n // If we have this week day just merge the event ids.\n $new_events[$event['week-day']]['events_ids'] = array_merge(\n $new_events[$event['week-day']]['events_ids'],\n $event['events_ids']\n );\n } else {\n $new_events[$event['week-day']] = $event;\n }\n}\n\n$new_events = array_values($new_events);\n</code></pre>\n\n<p>If the events in the initial array are not events just from one week you should focus on the <code>day-date</code> - associate all events IDs with it and then you can easily get the weekday name for that unique date. That approach would be much more versatile.</p>\n"
}
] |
2017/11/27
|
[
"https://wordpress.stackexchange.com/questions/287078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130304/"
] |
```
Array (
[0] => Array ( [week-day] => tuesday [day-date] => 1511841600 [events_ids] => Array ( [0] => 83417 ) )
[1] => Array ( [week-day] => wednesday [day-date] => 1511913600 [events_ids] => Array ( [0] => 83417 ) )
[2] => Array ( [week-day] => thrusday [day-date] => 1512000000 [events_ids] => Array ( [0] => 83417 ) )
[3] => Array ( [week-day] => tuesday [day-date] => 1511830800 [events_ids] => Array ( [0] => 83411 ) )
)
```
How do I get the first value `tuesday` of key `week-day` and combine all `events_ids` of all tuesdays?
|
This should get the desired result:
```
//Initial Array
$events = array
(
array
(
'week-day' => 'tuesday',
'day-date' => 1511841600,
'events_ids' => array( 83417 )
),
array
(
'week-day' => 'wednesday',
'day-date' => 1511913600,
'events_ids' => array( 83419, 12345 )
),
array
(
'week-day' => 'tuesday',
'day-date' => 1511830800,
'events_ids' => array( 83411 )
)
);
//Array to fill
$tuesday_event_ids = array();
foreach($events as $event ):
//if day is tuesday & we have event IDs
if($event['week-day'] === 'tuesday' && count($event['events_ids'])):
foreach($event['events_ids'] as $id):
//Push to array if not already in it
if(!in_array($id,$tuesday_event_ids))
array_push($tuesday_event_ids, $id);
endforeach;
endif;
endforeach;
//should be: array(83417,83411)
var_dump($tuesday_event_ids);
```
side note: you may want to consider changing the array keys to either be all `-` based or all `_` based for sanity.
|
287,104 |
<p>This is the main requirements of my project.</p>
<p>After a user login, logout should be done only if user click logout button or if user delete browser history.</p>
<p>When browser closing, then machine restarting, changing IP address <strong>should NOT logout the User</strong>.</p>
<p>Is this possible with WordPress? Is there any filter, action hook?</p>
|
[
{
"answer_id": 287108,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": -1,
"selected": false,
"text": "<p>You can try setting cookies when a user logs in using <code>wp_set_auth_cookie</code>.</p>\n\n<p>Something like : </p>\n\n<pre><code>add_action( 'wp_login', function($login, $user){\n wp_set_auth_cookie($user->ID, TRUE);\n}, 10, 2 );\n</code></pre>\n\n<p>Note: Code is not tested or tried. Please check for errors.</p>\n"
},
{
"answer_id": 287114,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>auth_cookie_expiration</code> filter to change the expiration time of the cookie WordPress sets to remember you. The user won't be logged out unless they change browser or clear their cookies (normally part of clearing history).</p>\n\n<p>The problem is that you can't set a cookie to never expire, so you have to set a date in the far future. The furthest you can go is 19th January 2038, because of the <a href=\"https://en.wikipedia.org/wiki/Year_2038_problem\" rel=\"nofollow noreferrer\">Year 2038 problem</a>.</p>\n\n<p>The value of the <code>auth_cookie_expiration</code> filter is added to <code>time()</code> so if you want to set the longest possible time for the cookie, you need to get the maximum value (<code>2147483647</code> according to <a href=\"https://stackoverflow.com/a/22479460/2684861\">this</a>) and subtract <code>time()</code>:</p>\n\n<pre><code>function wpse_287104_cookie_expiration( $length ) {\n return time() - 2147483647;\n}\nadd_filter( 'auth_cookie_expiration', 'wpse_287104_cookie_expiration' );\n</code></pre>\n"
},
{
"answer_id": 336440,
"author": "nicolas181070",
"author_id": 154703,
"author_profile": "https://wordpress.stackexchange.com/users/154703",
"pm_score": 0,
"selected": false,
"text": "<p>I used this code in wordpress functions.php, to auto logout customer/user after payment in woocommerce or close the browser</p>\n\n<pre><code>function logged_in( $expirein ) {\n return 6; // 6 in seconds\n}\nadd_filter( 'auth_cookie_expiration', 'logged_in' );\n\nfunction wp_logout2() {\n wp_destroy_current_session();\n wp_clear_auth_cookie();\n\n /**\n * Fires after a user is logged-out.\n *\n * @since 1.5.0\n */\n do_action( 'wp_logout2' );\n}\n\nfunction wpse108399_change_cookie_logout( $expiration, $user_id, $remember ){\n if( $remember && user_can( $user_id, 'administrator' ) ){\n $expiration = 604800;// yes, I know this is 1 minute\n }\n if( $remember && user_can( $user_id, 'editor' ) ){\n $expiration = 604800;// yes, I know this is 1 minute\n }\n }\n return $expiration;\n}\nadd_filter( 'auth_cookie_expiration','wpse108399_change_cookie_logout', 10, 3 );\n\n/**\n * Bypass logout confirmation.\n */\nfunction iconic_bypass_logout_confirmation() {\n global $wp;\n\n if ( isset( $wp->query_vars['customer-logout'] ) ) {\n wp_redirect( str_replace( '&amp;', '&', wp_logout_url( wc_get_page_permalink( 'myaccount' ) ) ) );\n exit;\n }\n}\n\nadd_action( 'template_redirect', 'iconic_bypass_logout_confirmation' );\n</code></pre>\n\n<p>A part of this code it's for increase expiration time to administrators of wordpress or other kinds of user </p>\n\n<pre><code>function wpse108399_change_cookie_logout( $expiration, $user_id, $remember ){\n if( $remember && user_can( $user_id, 'administrator' ) ){\n $expiration = 604800;// yes, I know this is 1 minute\n }\n if( $remember && user_can( $user_id, 'editor' ) ){\n $expiration = 604800;// yes, I know this is 1 minute\n }\n }\n return $expiration;\n}\nadd_filter( 'auth_cookie_expiration','wpse108399_change_cookie_logout', 10, 3 );\n</code></pre>\n"
}
] |
2017/11/28
|
[
"https://wordpress.stackexchange.com/questions/287104",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
] |
This is the main requirements of my project.
After a user login, logout should be done only if user click logout button or if user delete browser history.
When browser closing, then machine restarting, changing IP address **should NOT logout the User**.
Is this possible with WordPress? Is there any filter, action hook?
|
You can use the `auth_cookie_expiration` filter to change the expiration time of the cookie WordPress sets to remember you. The user won't be logged out unless they change browser or clear their cookies (normally part of clearing history).
The problem is that you can't set a cookie to never expire, so you have to set a date in the far future. The furthest you can go is 19th January 2038, because of the [Year 2038 problem](https://en.wikipedia.org/wiki/Year_2038_problem).
The value of the `auth_cookie_expiration` filter is added to `time()` so if you want to set the longest possible time for the cookie, you need to get the maximum value (`2147483647` according to [this](https://stackoverflow.com/a/22479460/2684861)) and subtract `time()`:
```
function wpse_287104_cookie_expiration( $length ) {
return time() - 2147483647;
}
add_filter( 'auth_cookie_expiration', 'wpse_287104_cookie_expiration' );
```
|
287,203 |
<p>I created the rewrite rule</p>
<pre><code>add_rewrite_rule("^user/(\d+)/(myaccount)/?", 'index.php?pagename=$matches[2]&user_id=$matches[1]','top');
</code></pre>
<p>So when a user visits example.com/user/123/myaccount/ it should use the wordpress page with slug 'myaccount' and pass '123' as the user_id.</p>
<p>I have flushed my rewrite rules, and I am using Monkeyman Rewrite Analyzer to check but it doesn't seem to match that pattern.</p>
<p>Can anyone point out what I'm doing wrong?</p>
|
[
{
"answer_id": 287219,
"author": "hashtagerrors",
"author_id": 102412,
"author_profile": "https://wordpress.stackexchange.com/users/102412",
"pm_score": -1,
"selected": false,
"text": "<p>Your rewrite rule <code>user/(\\d+)/(myaccount)/</code> had an error because of forward slashes. In regular expressions, \"/\" is a special character which needs to be escaped, which you can do by adding a backslash(/). So your rewrite rule may look something like this:</p>\n\n<pre><code>^user\\/(\\d+)\\/(myaccount)\\/?\n</code></pre>\n\n<p>I hope this solves your issue.</p>\n"
},
{
"answer_id": 287224,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>I tested the suggestion from my comment and it worked. </p>\n\n<p>Remove the brackets from <code>(myaccount)</code> and change <code>$matches[2]</code> in the URL to <code>myaccount</code>:</p>\n\n<pre><code>function wpse_287203_rewrite_rule() {\n add_rewrite_rule( '^user/(\\d+)/myaccount/?', 'index.php?pagename=myaccount&user_id=$matches[1]', 'top' );\n}\nadd_action( 'init', 'wpse_287203_rewrite_rule' );\n</code></pre>\n\n<p><code>(myaccount)</code> will not match a whole world. That's a little more involved. See <a href=\"https://stackoverflow.com/a/4722036/2684861\">this Stack Overflow answer</a> for how to match an exact word. We don't need to do that here though, since we can just manually put the word into the second argument of <code>add_rewrite_rule()</code>.</p>\n\n<p>Also, it wasn't part of the question, but it's what comes next. To get access to the <code>user_id</code>, you need to add it to the list of valid query variables:</p>\n\n<pre><code>function wpse_287203_query_vars( $vars ) {\n $vars[] = 'user_id';\n\n return $vars;\n}\nadd_filter( 'query_vars', 'wpse_287203_query_vars' );\n</code></pre>\n\n<p>Now you can get the user id when on that URL with <code>get_query_var()</code>:</p>\n\n<pre><code>$user_id = get_query_var( 'user_id' );\n$userdata = get_userdata( $user_id );\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287203",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74060/"
] |
I created the rewrite rule
```
add_rewrite_rule("^user/(\d+)/(myaccount)/?", 'index.php?pagename=$matches[2]&user_id=$matches[1]','top');
```
So when a user visits example.com/user/123/myaccount/ it should use the wordpress page with slug 'myaccount' and pass '123' as the user\_id.
I have flushed my rewrite rules, and I am using Monkeyman Rewrite Analyzer to check but it doesn't seem to match that pattern.
Can anyone point out what I'm doing wrong?
|
I tested the suggestion from my comment and it worked.
Remove the brackets from `(myaccount)` and change `$matches[2]` in the URL to `myaccount`:
```
function wpse_287203_rewrite_rule() {
add_rewrite_rule( '^user/(\d+)/myaccount/?', 'index.php?pagename=myaccount&user_id=$matches[1]', 'top' );
}
add_action( 'init', 'wpse_287203_rewrite_rule' );
```
`(myaccount)` will not match a whole world. That's a little more involved. See [this Stack Overflow answer](https://stackoverflow.com/a/4722036/2684861) for how to match an exact word. We don't need to do that here though, since we can just manually put the word into the second argument of `add_rewrite_rule()`.
Also, it wasn't part of the question, but it's what comes next. To get access to the `user_id`, you need to add it to the list of valid query variables:
```
function wpse_287203_query_vars( $vars ) {
$vars[] = 'user_id';
return $vars;
}
add_filter( 'query_vars', 'wpse_287203_query_vars' );
```
Now you can get the user id when on that URL with `get_query_var()`:
```
$user_id = get_query_var( 'user_id' );
$userdata = get_userdata( $user_id );
```
|
287,216 |
<p>The description for <code>register_uninstall_hook</code>'s <code>$callback</code> parameter states:</p>
<blockquote>
<p>Must be a static method or function.<sup><a href="https://github.com/WordPress/WordPress/blob/05d60f74edf749467e8441c31c33c7fdbbd41e1d/wp-includes/plugin.php#L805-L806" rel="noreferrer">1</a></sup></p>
</blockquote>
<p>There is no such comment for <code>register_activation_hook</code> or <code>register_deactivation_hook</code>. However, in the Codex entry for <code>register_activation_hook</code> there is an example that reads:</p>
<blockquote>
<p>Or, because the activation hook requires a static function, if you're inside of a __construct():<sup><a href="https://codex.wordpress.org/Function_Reference/register_activation_hook" rel="noreferrer">2</a></sup></p>
</blockquote>
<p>In a GitHub issue, "why is activate a static method?", a user states:</p>
<blockquote>
<p>You can't define them as standard functions because they require an instance of the plugin to fire, but you can't instantiate the plugin prior to firing the activation function because the constructor will fire (even if it's empty), so functions need to be marked as static so that any preliminary work required to prepare the plugin for de/activation can be set.<sup><a href="https://github.com/DevinVinson/WordPress-Plugin-Boilerplate/issues/178#issuecomment-40083265" rel="noreferrer">3</a></sup></p>
</blockquote>
<p>When using classes to (de)activate a plugin, are the functions required to be static? If so, is the explanation as to why correct?</p>
|
[
{
"answer_id": 340234,
"author": "Lucas Vendramini",
"author_id": 168637,
"author_profile": "https://wordpress.stackexchange.com/users/168637",
"pm_score": 2,
"selected": false,
"text": "<p>Depends the way you want to implement it. The static is used because you don't have to instantiate the class to use the functions of the class. It's up to you. I generally would do:</p>\n\n<pre><code><?php\n\n/*it's good practice that every class has its own file. So put it in for example 'classes/class-hooks.php' and require it properly in your plugin file. */\n\nclass Hooks{\n static function activation(){\n //the code you want to execute when the plugin activates\n }\n\n static function deactivation(){\n //the code you want to execute when the plugin deactivates\n }\n\n static function uninstall(){\n //the code you want to execute when the plugin uninstalled\n }\n\n}\n\n...\n\n// you should use this in your plugin file\n\nregister_activation_hook(__FILE__, 'Hooks::activation' );\nregister_deactivation_hook(__FILE__, 'Hooks::deactivation');\nregister_uninstall_hook(__FILE__, 'Hooks::uninstall');\n\n\n</code></pre>\n\n<p>This is the simple way I know to do it and the plugins I read the code generally does that way. Hope that helps!</p>\n"
},
{
"answer_id": 349586,
"author": "Madiop Niang",
"author_id": 175849,
"author_profile": "https://wordpress.stackexchange.com/users/175849",
"pm_score": 0,
"selected": false,
"text": "<h2>In my plugin folder I have created a folder named includes who have two files php</h2>\n\n<p><strong>#1 = my-plugin-activate.php</strong></p>\n\n<pre><code><?php\n/**\n * @package MyPlugin\n */\n\nclass MyPluginActivate {\n public static function activate() {\n flush_rewrite_rules();\n }\n} \n</code></pre>\n\n<p><strong>#2 - my-plugin-desactivate.php</strong></p>\n\n<pre><code><?php\n/**\n * @package MyPlugin\n */\n\nclass MyPluginDeactivate {\n public static function deactivate() {\n flush_rewrite_rules();\n }\n} \n</code></pre>\n\n<h3>In my principal file php : my-plugin.php I have required this two file in the bottom of the <em>class MyPlugin</em></h3>\n\n<ol>\n<li><p>we must first instantiate the class and register it</p>\n\n<p>$fm = new MyPlugin(); </p>\n\n<p>$fm->register();</p></li>\n<li><p>there are two methode to require the file externe activate.php and deactivate.php</p>\n\n<p>register_activation_hook( <strong>FILE</strong>, array( $fm, 'activate' ) );</p>\n\n<p>or</p>\n\n<p>require_once plugin_dir_path( <strong>FILE</strong> ) . 'includes/my-plugin-activate.php';\nregister_desactivation_hook( <strong>FILE</strong>, array( 'MyPluginActivate', 'activate' ) );</p></li>\n</ol>\n\n<p>it's the same for Deactivate</p>\n\n<p><a href=\"https://i.stack.imgur.com/z0wgW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z0wgW.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59643/"
] |
The description for `register_uninstall_hook`'s `$callback` parameter states:
>
> Must be a static method or function.[1](https://github.com/WordPress/WordPress/blob/05d60f74edf749467e8441c31c33c7fdbbd41e1d/wp-includes/plugin.php#L805-L806)
>
>
>
There is no such comment for `register_activation_hook` or `register_deactivation_hook`. However, in the Codex entry for `register_activation_hook` there is an example that reads:
>
> Or, because the activation hook requires a static function, if you're inside of a \_\_construct():[2](https://codex.wordpress.org/Function_Reference/register_activation_hook)
>
>
>
In a GitHub issue, "why is activate a static method?", a user states:
>
> You can't define them as standard functions because they require an instance of the plugin to fire, but you can't instantiate the plugin prior to firing the activation function because the constructor will fire (even if it's empty), so functions need to be marked as static so that any preliminary work required to prepare the plugin for de/activation can be set.[3](https://github.com/DevinVinson/WordPress-Plugin-Boilerplate/issues/178#issuecomment-40083265)
>
>
>
When using classes to (de)activate a plugin, are the functions required to be static? If so, is the explanation as to why correct?
|
Depends the way you want to implement it. The static is used because you don't have to instantiate the class to use the functions of the class. It's up to you. I generally would do:
```
<?php
/*it's good practice that every class has its own file. So put it in for example 'classes/class-hooks.php' and require it properly in your plugin file. */
class Hooks{
static function activation(){
//the code you want to execute when the plugin activates
}
static function deactivation(){
//the code you want to execute when the plugin deactivates
}
static function uninstall(){
//the code you want to execute when the plugin uninstalled
}
}
...
// you should use this in your plugin file
register_activation_hook(__FILE__, 'Hooks::activation' );
register_deactivation_hook(__FILE__, 'Hooks::deactivation');
register_uninstall_hook(__FILE__, 'Hooks::uninstall');
```
This is the simple way I know to do it and the plugins I read the code generally does that way. Hope that helps!
|
287,255 |
<p>How do I display a rating at all times, even if it is empty? This is for woocommerce, meant for product boxes like popular products and new products, doesn't have to show up on single product pages.</p>
|
[
{
"answer_id": 320620,
"author": "Fatema Tuz Zuhora",
"author_id": 155001,
"author_profile": "https://wordpress.stackexchange.com/users/155001",
"pm_score": 1,
"selected": false,
"text": "<p>Add the following code to your functions.php</p>\n\n<pre><code>add_action('woocommerce_after_shop_loop_item_title','change_loop_ratings_location', 2 );\nfunction change_loop_ratings_location(){\nremove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_rating', 5 );\nadd_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_rating', 15 );\n}\n</code></pre>\n\n<p>And then after add the following lines also to get the rating count</p>\n\n<pre><code>add_filter( 'woocommerce_product_get_rating_html', 'loop_product_get_rating_html', 20, 3 );\nfunction loop_product_get_rating_html( $html, $rating, $count ){\n if ( 0 < $rating && ! is_product() ) {\n global $product;\n $rating_cnt = array_sum($product->get_rating_counts());\n $count_html = ' <div class=\"count-rating\">' . $rating_cnt .'</div>';\n\n $html = '<div class=\"container-rating\"><div class=\"star-rating\">';\n $html .= wc_get_star_rating_html( $rating, $count );\n $html .= '</div>' . $count_html . '</div>';\n }\n return $html;\n}\n</code></pre>\n"
},
{
"answer_id": 400846,
"author": "amin",
"author_id": 217487,
"author_profile": "https://wordpress.stackexchange.com/users/217487",
"pm_score": 0,
"selected": false,
"text": "<p>try this in your functions.php:</p>\n<pre><code>add_filter('woocommerce_product_get_rating_html',function ( $html, $rating, $count){\n $label = sprintf( __( 'Rated %s out of 5', 'woocommerce' ), $rating );\n $html ='<div class="star-rating" role="img" aria-label="' . esc_attr( $label ) . '">' . wc_get_star_rating_html( $rating, $count ) . '</div>';\n return $html;\n},9999,3);\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287255",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132231/"
] |
How do I display a rating at all times, even if it is empty? This is for woocommerce, meant for product boxes like popular products and new products, doesn't have to show up on single product pages.
|
Add the following code to your functions.php
```
add_action('woocommerce_after_shop_loop_item_title','change_loop_ratings_location', 2 );
function change_loop_ratings_location(){
remove_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_rating', 5 );
add_action('woocommerce_after_shop_loop_item_title','woocommerce_template_loop_rating', 15 );
}
```
And then after add the following lines also to get the rating count
```
add_filter( 'woocommerce_product_get_rating_html', 'loop_product_get_rating_html', 20, 3 );
function loop_product_get_rating_html( $html, $rating, $count ){
if ( 0 < $rating && ! is_product() ) {
global $product;
$rating_cnt = array_sum($product->get_rating_counts());
$count_html = ' <div class="count-rating">' . $rating_cnt .'</div>';
$html = '<div class="container-rating"><div class="star-rating">';
$html .= wc_get_star_rating_html( $rating, $count );
$html .= '</div>' . $count_html . '</div>';
}
return $html;
}
```
|
287,281 |
<p>I have worked four hours on this but with no result.
There is a custom taxonomy and I need to display the image of the child category but displays the image of parent category.</p>
<p>My code is:</p>
<pre><code><?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$queried_object = get_queried_object();
$term_id = get_queried_object() -> term_id;
$taxonomyName = "product-categories";
$termchildren = get_term_children( $term_id, $taxonomyName );
$image_id = get_term_meta( $term_id, 'showcase-taxonomy-image-id', true );
if ($termchildren != false){
foreach ($termchildren as $child) {
$term2 = get_term_by( 'id', $child, $taxonomyName );
?>
<div class="row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block">
<img class="img-fluid imgborder" src="<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>" alt="<?php echo $term2 -> name; ?>">
<h2><a href="<?php echo get_term_link($child, $taxonomyName); ?>"><?php echo $term2 -> name; ?></a></h2>
</div>
</code></pre>
<p>I know the problem is in this line, but I don't know what exactly I should do.</p>
<pre><code> $image_id = get_term_meta( $term_id, 'showcase-taxonomy-image-id', true );
</code></pre>
<p>I would appreciate if anyone can help me.</p>
|
[
{
"answer_id": 287286,
"author": "Narek Zakarian",
"author_id": 92573,
"author_profile": "https://wordpress.stackexchange.com/users/92573",
"pm_score": -1,
"selected": false,
"text": "<p>Instead of <code>$term_id</code>, you have to use <code>$termchildren</code> id and put it in foreach loop</p>\n\n<pre><code>if (! empty ( $term_children ) ){\nforeach ($termchildren as $child) {\n $image_id = get_term_meta( $child, 'showcase-taxonomy-image-id', true );?>\n <div class=\"row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block\">\n <img class=\"img-fluid imgborder\" src=\"<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>\" alt=\"<?php echo $child->name; ?>\">\n <h2><a href=\"<?php echo get_term_link($child, $taxonomyName); ?>\"><?php echo $child->name; ?></a></h2>\n </div>\n</code></pre>\n\n<p>\n"
},
{
"answer_id": 287289,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>You just need to move the setting of the <code>$image_id</code> value within the <code>foreach</code> loop so that the image is retrieved for each child term.</p>\n\n<p>Here's complete code with that change made and a few others:</p>\n\n<pre><code>$queried_object = get_queried_object();\n$term_children = get_term_children( $queried_object->term_id, $queried_object->taxonomy );\n\nif ( ! empty ( $term_children ) ) :\n foreach ( $term_children as $term_id ) :\n $term = get_term_by( 'id', $term_id, $queried_object->taxonomy );\n $image_id = get_term_meta( $term_id, 'showcase-taxonomy-image-id', true );\n ?>\n\n <div class=\"row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block\">\n <?php echo wp_get_attachment_image( $image_id, 'thumbnail', false, array( 'class' => 'img-fluid imgborder' ) ); ?>\n <h2><a href=\"<?php echo esc_url( get_term_link( $term_id ) ); ?>\"><?php echo $term->name; ?></a></h2>\n </div>\n\n <?php\n endforeach;\nendif;\n</code></pre>\n\n<p>Note some of the other changes I made:</p>\n\n<ol>\n<li>I got rid of unnecessary values from the beginning and just used <code>get_queried_object()</code> to get the term object for the current term, and used its properties for getting the term children.</li>\n<li>I checked that <code>$term_children</code> wasn't <em>empty</em>, instead of false. <code>get_term_children()</code> will never return an actual <code>false</code> value, so <code>! empty()</code> is a more accurate representation of what you're checking for.</li>\n<li>I set <code>$image_id</code> inside the <code>foreach</code> loop with the current <code>$term_id</code> for the child term.</li>\n<li>I used <code>wp_get_attachment_image()</code> instead of <code>wp_get_attachment_image_url()</code> because I find it neater than mixing up PHP in HTML attributes.</li>\n<li>I used <code>esc_url()</code> on <code>get_term_link()</code> for the extra layer of safety, and I also removed the taxonomy argument from <code>get_term_link()</code> because it's not needed and it keeps the code shorter.</li>\n</ol>\n"
},
{
"answer_id": 287290,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 2,
"selected": false,
"text": "<p>Haven't tested it, but this should do it.</p>\n\n<pre><code> <?php\n\n$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );\n$queried_object = get_queried_object();\n$term_id = get_queried_object() -> term_id;\n$taxonomyName = \"product-categories\";\n$termchildren = get_term_children( $term_id, $taxonomyName );\n\n\n\nif (! empty ( $term_children ) ){\n foreach ($termchildren as $child) {\n $image_id = get_term_meta( $child, 'showcase-taxonomy-image-id', true );?>\n <div class=\"row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block\">\n <img class=\"img-fluid imgborder\" src=\"<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>\" alt=\"<?php echo $child->name; ?>\">\n <h2><a href=\"<?php echo get_term_link($child, $taxonomyName); ?>\"><?php echo $child->name; ?></a></h2>\n </div>\n <?php }\n?>\n</code></pre>\n"
},
{
"answer_id": 287311,
"author": "vesta",
"author_id": 132338,
"author_profile": "https://wordpress.stackexchange.com/users/132338",
"pm_score": 0,
"selected": false,
"text": "<p>works wonderful... thank you Jacob Peattie and Daniel Fonda :)</p>\n\n<pre><code><?php\n\n$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );\n$queried_object = get_queried_object();\n$term_id = get_queried_object() -> term_id;\n$taxonomyName = \"product-categories\";\n$termchildren = get_term_children( $term_id, $taxonomyName );\n\nif ($termchildren != false){\n foreach ($termchildren as $child) {\n $term2 = get_term_by( 'id', $child, $taxonomyName );\n $image_id = get_term_meta( $child, 'showcase-taxonomy-image-id', true );\n?>\n\n<div class=\"row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block\"> \n <img class=\"img-fluid imgborder\" src=\"<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>\" alt=\"<?php echo $term2 -> name; ?>\">\n <h2 class=\"p-4\"><a href=\"<?php echo get_term_link($child, $taxonomyName); ?>\"><?php echo $term2 -> name; ?></a></h2>\n</div>\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132336/"
] |
I have worked four hours on this but with no result.
There is a custom taxonomy and I need to display the image of the child category but displays the image of parent category.
My code is:
```
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$queried_object = get_queried_object();
$term_id = get_queried_object() -> term_id;
$taxonomyName = "product-categories";
$termchildren = get_term_children( $term_id, $taxonomyName );
$image_id = get_term_meta( $term_id, 'showcase-taxonomy-image-id', true );
if ($termchildren != false){
foreach ($termchildren as $child) {
$term2 = get_term_by( 'id', $child, $taxonomyName );
?>
<div class="row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block">
<img class="img-fluid imgborder" src="<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>" alt="<?php echo $term2 -> name; ?>">
<h2><a href="<?php echo get_term_link($child, $taxonomyName); ?>"><?php echo $term2 -> name; ?></a></h2>
</div>
```
I know the problem is in this line, but I don't know what exactly I should do.
```
$image_id = get_term_meta( $term_id, 'showcase-taxonomy-image-id', true );
```
I would appreciate if anyone can help me.
|
Haven't tested it, but this should do it.
```
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$queried_object = get_queried_object();
$term_id = get_queried_object() -> term_id;
$taxonomyName = "product-categories";
$termchildren = get_term_children( $term_id, $taxonomyName );
if (! empty ( $term_children ) ){
foreach ($termchildren as $child) {
$image_id = get_term_meta( $child, 'showcase-taxonomy-image-id', true );?>
<div class="row col-xl-3 col-lg-3 col-md-3 col-sm-12 col-12 d-inline-block">
<img class="img-fluid imgborder" src="<?php echo wp_get_attachment_image_url( $image_id, '' ); ?>" alt="<?php echo $child->name; ?>">
<h2><a href="<?php echo get_term_link($child, $taxonomyName); ?>"><?php echo $child->name; ?></a></h2>
</div>
<?php }
?>
```
|
287,284 |
<p>Is there a way to make it so Everyone can see comments, But only the post author or those belonging to the Premium role can post a comment? </p>
<p>Could I do something like </p>
<pre><code> global $current_user;
get_currentuserinfo();
if (is_user_logged_in() && $current_user->ID == $post->post_author) { comment_form();
} else {
if( $current_user->roles[0] == 'admin' || $current_user->roles[0] == 'premium' )
{ comment_form(); } endif;
else {
echo '<h4>You are not allowed to post comments.</h4>';
}
</code></pre>
<p>Sorry I should have said, there are two roles, basic and premium. Both can make posts. But Only premium can comment on anyones posts, and Basic can only comment on their own posts</p>
|
[
{
"answer_id": 287287,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 1,
"selected": false,
"text": "<p>Good news, bad news..</p>\n\n<p><strong>Good news</strong>\nThe logic behind it is really simple. You basically wrap the form inside of a simple if statement.</p>\n\n<pre><code> if(condition){ \n /*Your form here*/\n } \n else {echo '<h4>You need to be a premium account to post comments</h4>';}\n</code></pre>\n\n<p><strong>Bad News</strong>\nYou'll need to code in another user role. This can usually be done via a plugin. Most plugins offer documentation on how to check for a user's user-role.</p>\n\n<p>So if the plugin has a function like </p>\n\n<pre><code>get_user_role();\n</code></pre>\n\n<p>You'd simply place that as your condition. That would look something like this:</p>\n\n<pre><code> if(get_user_role() == 'premium'){ \n /*Your form here*/\n } \n else {echo '<h4>You need to be a premium account to post comments</h4>';}\n</code></pre>\n"
},
{
"answer_id": 287293,
"author": "Tim Hallman",
"author_id": 38375,
"author_profile": "https://wordpress.stackexchange.com/users/38375",
"pm_score": 0,
"selected": false,
"text": "<p>In your comments.php template replace <code>comment_form()</code> with this:</p>\n\n<pre><code>if (current_user_can('manage_options') and current_user_can('Premium') {\n comment_form(); \n}\n</code></pre>\n"
},
{
"answer_id": 287296,
"author": "Elyes At.",
"author_id": 117786,
"author_profile": "https://wordpress.stackexchange.com/users/117786",
"pm_score": 0,
"selected": false,
"text": "<p>Replace the <code>comment_form()</code> in <code>comments.php</code> file with this code:</p>\n\n<pre><code>$user = wp_get_current_user();\nif( $user->roles[0] == 'admin' || $user->roles[0] == 'premium' ){\n // show comment form\n comment_form(); \n} else {\n echo '<h4>You are not allowed to post comments.</h4>';\n}\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129681/"
] |
Is there a way to make it so Everyone can see comments, But only the post author or those belonging to the Premium role can post a comment?
Could I do something like
```
global $current_user;
get_currentuserinfo();
if (is_user_logged_in() && $current_user->ID == $post->post_author) { comment_form();
} else {
if( $current_user->roles[0] == 'admin' || $current_user->roles[0] == 'premium' )
{ comment_form(); } endif;
else {
echo '<h4>You are not allowed to post comments.</h4>';
}
```
Sorry I should have said, there are two roles, basic and premium. Both can make posts. But Only premium can comment on anyones posts, and Basic can only comment on their own posts
|
Good news, bad news..
**Good news**
The logic behind it is really simple. You basically wrap the form inside of a simple if statement.
```
if(condition){
/*Your form here*/
}
else {echo '<h4>You need to be a premium account to post comments</h4>';}
```
**Bad News**
You'll need to code in another user role. This can usually be done via a plugin. Most plugins offer documentation on how to check for a user's user-role.
So if the plugin has a function like
```
get_user_role();
```
You'd simply place that as your condition. That would look something like this:
```
if(get_user_role() == 'premium'){
/*Your form here*/
}
else {echo '<h4>You need to be a premium account to post comments</h4>';}
```
|
287,292 |
<p>I'm currently working on an Estate Agency website. Built the custom post type and some custom taxonomies.</p>
<p>I need to build a custom search where a user can select options from the custom taxonomies to display the search results.</p>
<p>Example: Search by location & min-max price & number of bedrooms.</p>
<p>I tried a couple of plugins for Real Estate but they don't allow me enough control over the display of the output in the frontend of the website, therefore I need to build my own "simple" custom search.</p>
<p>Can anybody point me in the direction of a tutorial, or how to do this. I don't want to use a plugin as I can't find one that isn't overkill or gives me enough space to output what I need.</p>
<p>Hoping somebody can help</p>
<p>Thanks in advance</p>
<p>Dan</p>
|
[
{
"answer_id": 287287,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 1,
"selected": false,
"text": "<p>Good news, bad news..</p>\n\n<p><strong>Good news</strong>\nThe logic behind it is really simple. You basically wrap the form inside of a simple if statement.</p>\n\n<pre><code> if(condition){ \n /*Your form here*/\n } \n else {echo '<h4>You need to be a premium account to post comments</h4>';}\n</code></pre>\n\n<p><strong>Bad News</strong>\nYou'll need to code in another user role. This can usually be done via a plugin. Most plugins offer documentation on how to check for a user's user-role.</p>\n\n<p>So if the plugin has a function like </p>\n\n<pre><code>get_user_role();\n</code></pre>\n\n<p>You'd simply place that as your condition. That would look something like this:</p>\n\n<pre><code> if(get_user_role() == 'premium'){ \n /*Your form here*/\n } \n else {echo '<h4>You need to be a premium account to post comments</h4>';}\n</code></pre>\n"
},
{
"answer_id": 287293,
"author": "Tim Hallman",
"author_id": 38375,
"author_profile": "https://wordpress.stackexchange.com/users/38375",
"pm_score": 0,
"selected": false,
"text": "<p>In your comments.php template replace <code>comment_form()</code> with this:</p>\n\n<pre><code>if (current_user_can('manage_options') and current_user_can('Premium') {\n comment_form(); \n}\n</code></pre>\n"
},
{
"answer_id": 287296,
"author": "Elyes At.",
"author_id": 117786,
"author_profile": "https://wordpress.stackexchange.com/users/117786",
"pm_score": 0,
"selected": false,
"text": "<p>Replace the <code>comment_form()</code> in <code>comments.php</code> file with this code:</p>\n\n<pre><code>$user = wp_get_current_user();\nif( $user->roles[0] == 'admin' || $user->roles[0] == 'premium' ){\n // show comment form\n comment_form(); \n} else {\n echo '<h4>You are not allowed to post comments.</h4>';\n}\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287292",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82343/"
] |
I'm currently working on an Estate Agency website. Built the custom post type and some custom taxonomies.
I need to build a custom search where a user can select options from the custom taxonomies to display the search results.
Example: Search by location & min-max price & number of bedrooms.
I tried a couple of plugins for Real Estate but they don't allow me enough control over the display of the output in the frontend of the website, therefore I need to build my own "simple" custom search.
Can anybody point me in the direction of a tutorial, or how to do this. I don't want to use a plugin as I can't find one that isn't overkill or gives me enough space to output what I need.
Hoping somebody can help
Thanks in advance
Dan
|
Good news, bad news..
**Good news**
The logic behind it is really simple. You basically wrap the form inside of a simple if statement.
```
if(condition){
/*Your form here*/
}
else {echo '<h4>You need to be a premium account to post comments</h4>';}
```
**Bad News**
You'll need to code in another user role. This can usually be done via a plugin. Most plugins offer documentation on how to check for a user's user-role.
So if the plugin has a function like
```
get_user_role();
```
You'd simply place that as your condition. That would look something like this:
```
if(get_user_role() == 'premium'){
/*Your form here*/
}
else {echo '<h4>You need to be a premium account to post comments</h4>';}
```
|
287,306 |
<p>This is probably an easy question but I'm having so much trouble figuring it out on my own.</p>
<p>I installed Storefront (the official Woocommerce theme) on a test server and I like it a lot, but the default front page (called Welcome) does not have a sidebar, which is a deal-breaker for me. I've been trying to add one with no luck, is this something that I'd need to do extensive template modifications to make work, or is there something easier (I'm fine with working with the PHP files and adding code and whatnot)</p>
|
[
{
"answer_id": 287313,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 1,
"selected": false,
"text": "<p>I think there's an option to include it via the customizer (appearance->themes->customize)</p>\n\n<p>If not, then you might need to open up content-homepage.php and put</p>\n\n<pre><code><?php get_sidebar(); ?>\n</code></pre>\n\n<p>Where you want to display the sidebar.</p>\n"
},
{
"answer_id": 287319,
"author": "Chazlie",
"author_id": 129681,
"author_profile": "https://wordpress.stackexchange.com/users/129681",
"pm_score": 0,
"selected": false,
"text": "<p>If you cant do it via customiser you should be able to set it via the template or create a new template called Home with sidebar using something like this</p>\n\n<pre><code> <?php\n/*\nTemplate name: Page - Home with Sidebar \n*/\nget_header(); ?>\n<div class=\"row\">\n\n<div id=\"content\" class=\"large-9 right col\" role=\"main\">\n <div class=\"page-inner\">\n<?php while ( have_posts() ) : the_post(); ?>\n\n <?php the_content(); ?>\n <?php endwhile; // end of the loop. ?>\n </div><!-- .page-inner -->\n</div><!-- end #content large-9 left -->\n\n<div class=\"large-3 col col-first col-divided\">\n<?php get_sidebar(); ?>\n</div><!-- end sidebar -->\n\n</div><!-- end row -->\n</code></pre>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132349/"
] |
This is probably an easy question but I'm having so much trouble figuring it out on my own.
I installed Storefront (the official Woocommerce theme) on a test server and I like it a lot, but the default front page (called Welcome) does not have a sidebar, which is a deal-breaker for me. I've been trying to add one with no luck, is this something that I'd need to do extensive template modifications to make work, or is there something easier (I'm fine with working with the PHP files and adding code and whatnot)
|
I think there's an option to include it via the customizer (appearance->themes->customize)
If not, then you might need to open up content-homepage.php and put
```
<?php get_sidebar(); ?>
```
Where you want to display the sidebar.
|
287,320 |
<p>I have an ACF custom field that depends on the value I need to change the page title, however, I cannot affect the page title, it appears my code is running after the page title is generated.</p>
<p>To explain my requirements. This is a real estate site where some listings are confidential, they flag it as such in the admin, the frontend should only show a small amount of data to logged out users.</p>
<p>Heres the latest code ive tried:</p>
<pre><code>add_filter('init', 'my_custom_title');
function my_custom_title( $title ){
global $post;
//var_dump($post);
echo $post->ID;
$hide_price = get_field("hide_price");
echo get_field("beds",$post->ID);
$view_hidden = get_field('view_hidden_listings', 'user_'. get_current_user_id() );
if($view_hidden == 1) {
$hide_price = 0;
}
if( $post->post_type == 'sales_listings' && $hide_price == 1) {
return "Confidential";
}
echo $view_hidden;
}
</code></pre>
<p>Any help is greatly appreciated, I've been requesting support from the ACF guys but they are unable to help.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 287329,
"author": "Elyes At.",
"author_id": 117786,
"author_profile": "https://wordpress.stackexchange.com/users/117786",
"pm_score": 1,
"selected": false,
"text": "<p>In order to change the title, you need to use <code>the_title</code> filter, also if you want to determine if the user is logged in or not just use <code>is_user_logged_in()</code> function.</p>\n\n<pre><code>function my_custom_title( $title, $id = null ) {\n global $post;\n if( $post->post_type == 'sales_listings' && !is_user_logged_in() ) {\n $title = \"Confidential\";\n } \n return $title;\n}\nadd_filter( 'the_title', 'my_custom_title', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 287332,
"author": "freejack",
"author_id": 124757,
"author_profile": "https://wordpress.stackexchange.com/users/124757",
"pm_score": 2,
"selected": false,
"text": "<p>If you refer to the post title you need to hook your function to the_title filter like explained in the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title\" rel=\"nofollow noreferrer\">codex</a>.</p>\n\n<pre><code>add_filter('the_title', 'my_custom_title', 10, 2);\n</code></pre>\n\n<p>If you refer to the HTML meta in your page then you need to hook your function to document_title_parts filter explained <a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>add_filter('document_title_parts', 'my_custom_title', 10, 2);\n</code></pre>\n\n<p>The two filters work differently as the first passes the title as a string and the second an array which contains the title as well.\nSo depending on which one you need your code will need to be adapted to work accordingly.</p>\n\n<p>If you can explain better your needs a better answer can be given.</p>\n"
}
] |
2017/11/29
|
[
"https://wordpress.stackexchange.com/questions/287320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91132/"
] |
I have an ACF custom field that depends on the value I need to change the page title, however, I cannot affect the page title, it appears my code is running after the page title is generated.
To explain my requirements. This is a real estate site where some listings are confidential, they flag it as such in the admin, the frontend should only show a small amount of data to logged out users.
Heres the latest code ive tried:
```
add_filter('init', 'my_custom_title');
function my_custom_title( $title ){
global $post;
//var_dump($post);
echo $post->ID;
$hide_price = get_field("hide_price");
echo get_field("beds",$post->ID);
$view_hidden = get_field('view_hidden_listings', 'user_'. get_current_user_id() );
if($view_hidden == 1) {
$hide_price = 0;
}
if( $post->post_type == 'sales_listings' && $hide_price == 1) {
return "Confidential";
}
echo $view_hidden;
}
```
Any help is greatly appreciated, I've been requesting support from the ACF guys but they are unable to help.
Thanks!
|
If you refer to the post title you need to hook your function to the\_title filter like explained in the [codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title).
```
add_filter('the_title', 'my_custom_title', 10, 2);
```
If you refer to the HTML meta in your page then you need to hook your function to document\_title\_parts filter explained [here](https://developer.wordpress.org/reference/hooks/document_title_parts/).
```
add_filter('document_title_parts', 'my_custom_title', 10, 2);
```
The two filters work differently as the first passes the title as a string and the second an array which contains the title as well.
So depending on which one you need your code will need to be adapted to work accordingly.
If you can explain better your needs a better answer can be given.
|
287,347 |
<p>I'm having some trouble creating a shortcode that queries some posts. This is the basics of my code:</p>
<pre><code>function shortcode_equipment($atts, $content = null) {
$equipment = get_page_by_title($content, OBJECT, 'equipment');
$loop = new WP_Query( array(
'posts_per_page' => 1,
'post_type' => 'equipment',
'page_id' => $equipment->ID
) );
while( $loop->have_posts() ) { $loop->the_post();
*misc code*
wp_reset_postdata();
return $string;
}
}
add_shortcode( 'item', 'shortcode_equipment' );
</code></pre>
<p>Now, ordinarily, this works fine for 99% of my posts. It queries the post by what's written inside the [item]title goes here[/item] shortcode and then displays a custom tooltip/hover effect accordingly.</p>
<p>However, if my post title has an apostrophe in it (ex: Mal's Post), then it's breaking and just querying whatever the last post in that custom post type is.</p>
<p>So, how do I get this to work with apostrophes in the post titles?</p>
|
[
{
"answer_id": 287350,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": false,
"text": "<p>There's most likely an escaping issue happening there. Try to escape the title before passing it to your shortcode, by using <code>sanitize_title_for_query()</code>, <code>sanitize_title()</code> or even <code>esc_html()</code>:</p>\n\n<pre><code>$content = sanitize_title_for_query( $content );\n$equipment = get_page_by_title( $content, OBJECT, 'equipment' );\n</code></pre>\n\n<p>More information about escaping data can be found <a href=\"https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 287352,
"author": "Greg36",
"author_id": 64017,
"author_profile": "https://wordpress.stackexchange.com/users/64017",
"pm_score": 3,
"selected": true,
"text": "<p>Title <code>Hello world!@#$%^*(),.;:\\</code> will work but any title you enter containing <code>' \" < > &</code> characters won't work because in <code>$content</code> variable you have escaped <a href=\"http://php.net/manual/pl/function.htmlentities.php\" rel=\"nofollow noreferrer\">HTML entities</a> so Mal's Post becomes <code>Mal&#8217;s Post</code>.</p>\n\n<p>To bypass it you can use <a href=\"https://codex.wordpress.org/Function_Reference/sanitize_title\" rel=\"nofollow noreferrer\"><code>sanitize_title</code></a> function along with <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_path\" rel=\"nofollow noreferrer\"><code>get_page_by_path</code></a>.</p>\n\n<pre><code>function shortcode_equipment($atts, $content = null) {\n $path = sanitize_title($content);\n\n $equipment = get_page_by_path( $path, OBJECT, 'equipment');\n</code></pre>\n\n<p>Rest of code works as before.</p>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132377/"
] |
I'm having some trouble creating a shortcode that queries some posts. This is the basics of my code:
```
function shortcode_equipment($atts, $content = null) {
$equipment = get_page_by_title($content, OBJECT, 'equipment');
$loop = new WP_Query( array(
'posts_per_page' => 1,
'post_type' => 'equipment',
'page_id' => $equipment->ID
) );
while( $loop->have_posts() ) { $loop->the_post();
*misc code*
wp_reset_postdata();
return $string;
}
}
add_shortcode( 'item', 'shortcode_equipment' );
```
Now, ordinarily, this works fine for 99% of my posts. It queries the post by what's written inside the [item]title goes here[/item] shortcode and then displays a custom tooltip/hover effect accordingly.
However, if my post title has an apostrophe in it (ex: Mal's Post), then it's breaking and just querying whatever the last post in that custom post type is.
So, how do I get this to work with apostrophes in the post titles?
|
Title `Hello world!@#$%^*(),.;:\` will work but any title you enter containing `' " < > &` characters won't work because in `$content` variable you have escaped [HTML entities](http://php.net/manual/pl/function.htmlentities.php) so Mal's Post becomes `Mal’s Post`.
To bypass it you can use [`sanitize_title`](https://codex.wordpress.org/Function_Reference/sanitize_title) function along with [`get_page_by_path`](https://codex.wordpress.org/Function_Reference/get_page_by_path).
```
function shortcode_equipment($atts, $content = null) {
$path = sanitize_title($content);
$equipment = get_page_by_path( $path, OBJECT, 'equipment');
```
Rest of code works as before.
|
287,363 |
<p>Currently I am using a very standard loop, and wondering how can I make it to display something like this "<strong>Latest Posts (4 today)</strong>" which will update with the amount of posts from that specific category which are published per day.</p>
<pre><code><ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<span class="title"><?php the_title(); ?></span>
</a>
</li>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
</code></pre>
|
[
{
"answer_id": 287364,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <code>date_query</code> to get your posts from today,</p>\n\n<ol>\n<li><p><code>pre_get_posts</code></p>\n\n<p>function function_display_posts_today( $query ) {</p>\n\n<pre><code>if (!is_admin() && $query->is_main_query()) {\n\n $today = getdate();\n\n $query->set('date_query', array(\n array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n )\n )\n}\n</code></pre>\n\n<p>}\nadd_action( 'pre_get_posts', 'function_display_posts_today' );</p></li>\n<li><p>WP_Query</p></li>\n</ol>\n\n<blockquote>\n<pre><code>$today = getdate();\n$args = array(\n 'date_query' => array(\n array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n</blockquote>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">date_query</a>.</p>\n\n<p>UPDATE : </p>\n\n<p>To get number of posts, just write a custom query live above and your count will be,</p>\n\n<pre><code><?php echo $query->post_count; ?>\n</code></pre>\n\n<p>Hope this one helps :)</p>\n"
},
{
"answer_id": 287409,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>I think I have figured out the most efficient way to do this. The tricky part is that you need the query for posts within the date range to:</p>\n\n<p>A. Match the current query. If you're looking at a category or tag, you want to get the posts from that day in that category or tag.</p>\n\n<p>B. Not be limited by the current posts-per-page setting. If you post more than one page's worth of posts in a day, the number needs to reflect that.</p>\n\n<p>You also don't need to query all the post data associated with these posts. You're just after the count.</p>\n\n<p>The solution I've come up with is:</p>\n\n<ol>\n<li>Get the current query.</li>\n<li>Turn of pagination.</li>\n<li>Set it to return just post IDs.</li>\n<li>Add a date query to limit it to posts from the current day.</li>\n</ol>\n\n<p>It has been tested and works well.</p>\n\n<p>To do this, we can access <code>global $wp_query</code> then get <code>$wp_query->query_vars</code> for the current query arguments. Then we modify the arguments as I described above and pass the new arguments to <code>get_posts()</code>. Then we just count the results. This is a function that does this:</p>\n\n<pre><code>function wpse_287363_get_posts_today_count() {\n global $wp_query;\n\n // Get query arguments for current main query.\n $args = $wp_query->query_vars;\n\n // Set new values for relevant arguments.\n $arg_amendments = array(\n 'fields' => 'ids',\n 'nopaging' => true,\n 'date_query' => array(\n array(\n 'after' => 'today',\n 'before' => 'tomorrow - 1 second',\n 'inclusive' => true,\n ),\n ),\n );\n\n // Replace relevant arguments in existing arguments with amended arguments.\n $new_args = array_merge( $args, $arg_amendments );\n\n // Get posts with new arguments.\n $post_ids = get_posts( $new_args );\n\n // Count results.\n $count = count( $post_ids );\n\n // Return count.\n return $count;\n}\n</code></pre>\n\n<p>Now you can use <code>wpse_287363_get_posts_today_count()</code> to get the number of posts made on the current date, relevant to whichever archive you're viewing. </p>\n\n<p>So if you're on a category archive it will return the number of posts made today in that category. On a tag archive it will return the number of posts made today in that tag. It will even work on date archives and show the number of posts made today in a given year/month. If you're just on the blog page it will show the number of posts made today in any category or tag. It should even work with custom post type/taxonomy archives.</p>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124290/"
] |
Currently I am using a very standard loop, and wondering how can I make it to display something like this "**Latest Posts (4 today)**" which will update with the amount of posts from that specific category which are published per day.
```
<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<span class="title"><?php the_title(); ?></span>
</a>
</li>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
```
|
I think I have figured out the most efficient way to do this. The tricky part is that you need the query for posts within the date range to:
A. Match the current query. If you're looking at a category or tag, you want to get the posts from that day in that category or tag.
B. Not be limited by the current posts-per-page setting. If you post more than one page's worth of posts in a day, the number needs to reflect that.
You also don't need to query all the post data associated with these posts. You're just after the count.
The solution I've come up with is:
1. Get the current query.
2. Turn of pagination.
3. Set it to return just post IDs.
4. Add a date query to limit it to posts from the current day.
It has been tested and works well.
To do this, we can access `global $wp_query` then get `$wp_query->query_vars` for the current query arguments. Then we modify the arguments as I described above and pass the new arguments to `get_posts()`. Then we just count the results. This is a function that does this:
```
function wpse_287363_get_posts_today_count() {
global $wp_query;
// Get query arguments for current main query.
$args = $wp_query->query_vars;
// Set new values for relevant arguments.
$arg_amendments = array(
'fields' => 'ids',
'nopaging' => true,
'date_query' => array(
array(
'after' => 'today',
'before' => 'tomorrow - 1 second',
'inclusive' => true,
),
),
);
// Replace relevant arguments in existing arguments with amended arguments.
$new_args = array_merge( $args, $arg_amendments );
// Get posts with new arguments.
$post_ids = get_posts( $new_args );
// Count results.
$count = count( $post_ids );
// Return count.
return $count;
}
```
Now you can use `wpse_287363_get_posts_today_count()` to get the number of posts made on the current date, relevant to whichever archive you're viewing.
So if you're on a category archive it will return the number of posts made today in that category. On a tag archive it will return the number of posts made today in that tag. It will even work on date archives and show the number of posts made today in a given year/month. If you're just on the blog page it will show the number of posts made today in any category or tag. It should even work with custom post type/taxonomy archives.
|
287,372 |
<p>I have a wordpress website, where i am providing customers with user name and password to access my shop.</p>
<p>When a customer logs in, he can see the top wordpress admin bar as well. I dont want users added as "customers" through users>add new to see that bar. </p>
<p>How should i disable this? </p>
|
[
{
"answer_id": 287364,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <code>date_query</code> to get your posts from today,</p>\n\n<ol>\n<li><p><code>pre_get_posts</code></p>\n\n<p>function function_display_posts_today( $query ) {</p>\n\n<pre><code>if (!is_admin() && $query->is_main_query()) {\n\n $today = getdate();\n\n $query->set('date_query', array(\n array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n )\n )\n}\n</code></pre>\n\n<p>}\nadd_action( 'pre_get_posts', 'function_display_posts_today' );</p></li>\n<li><p>WP_Query</p></li>\n</ol>\n\n<blockquote>\n<pre><code>$today = getdate();\n$args = array(\n 'date_query' => array(\n array(\n 'year' => $today['year'],\n 'month' => $today['mon'],\n 'day' => $today['mday'],\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n</blockquote>\n\n<p>See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters\" rel=\"nofollow noreferrer\">date_query</a>.</p>\n\n<p>UPDATE : </p>\n\n<p>To get number of posts, just write a custom query live above and your count will be,</p>\n\n<pre><code><?php echo $query->post_count; ?>\n</code></pre>\n\n<p>Hope this one helps :)</p>\n"
},
{
"answer_id": 287409,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>I think I have figured out the most efficient way to do this. The tricky part is that you need the query for posts within the date range to:</p>\n\n<p>A. Match the current query. If you're looking at a category or tag, you want to get the posts from that day in that category or tag.</p>\n\n<p>B. Not be limited by the current posts-per-page setting. If you post more than one page's worth of posts in a day, the number needs to reflect that.</p>\n\n<p>You also don't need to query all the post data associated with these posts. You're just after the count.</p>\n\n<p>The solution I've come up with is:</p>\n\n<ol>\n<li>Get the current query.</li>\n<li>Turn of pagination.</li>\n<li>Set it to return just post IDs.</li>\n<li>Add a date query to limit it to posts from the current day.</li>\n</ol>\n\n<p>It has been tested and works well.</p>\n\n<p>To do this, we can access <code>global $wp_query</code> then get <code>$wp_query->query_vars</code> for the current query arguments. Then we modify the arguments as I described above and pass the new arguments to <code>get_posts()</code>. Then we just count the results. This is a function that does this:</p>\n\n<pre><code>function wpse_287363_get_posts_today_count() {\n global $wp_query;\n\n // Get query arguments for current main query.\n $args = $wp_query->query_vars;\n\n // Set new values for relevant arguments.\n $arg_amendments = array(\n 'fields' => 'ids',\n 'nopaging' => true,\n 'date_query' => array(\n array(\n 'after' => 'today',\n 'before' => 'tomorrow - 1 second',\n 'inclusive' => true,\n ),\n ),\n );\n\n // Replace relevant arguments in existing arguments with amended arguments.\n $new_args = array_merge( $args, $arg_amendments );\n\n // Get posts with new arguments.\n $post_ids = get_posts( $new_args );\n\n // Count results.\n $count = count( $post_ids );\n\n // Return count.\n return $count;\n}\n</code></pre>\n\n<p>Now you can use <code>wpse_287363_get_posts_today_count()</code> to get the number of posts made on the current date, relevant to whichever archive you're viewing. </p>\n\n<p>So if you're on a category archive it will return the number of posts made today in that category. On a tag archive it will return the number of posts made today in that tag. It will even work on date archives and show the number of posts made today in a given year/month. If you're just on the blog page it will show the number of posts made today in any category or tag. It should even work with custom post type/taxonomy archives.</p>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287372",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132310/"
] |
I have a wordpress website, where i am providing customers with user name and password to access my shop.
When a customer logs in, he can see the top wordpress admin bar as well. I dont want users added as "customers" through users>add new to see that bar.
How should i disable this?
|
I think I have figured out the most efficient way to do this. The tricky part is that you need the query for posts within the date range to:
A. Match the current query. If you're looking at a category or tag, you want to get the posts from that day in that category or tag.
B. Not be limited by the current posts-per-page setting. If you post more than one page's worth of posts in a day, the number needs to reflect that.
You also don't need to query all the post data associated with these posts. You're just after the count.
The solution I've come up with is:
1. Get the current query.
2. Turn of pagination.
3. Set it to return just post IDs.
4. Add a date query to limit it to posts from the current day.
It has been tested and works well.
To do this, we can access `global $wp_query` then get `$wp_query->query_vars` for the current query arguments. Then we modify the arguments as I described above and pass the new arguments to `get_posts()`. Then we just count the results. This is a function that does this:
```
function wpse_287363_get_posts_today_count() {
global $wp_query;
// Get query arguments for current main query.
$args = $wp_query->query_vars;
// Set new values for relevant arguments.
$arg_amendments = array(
'fields' => 'ids',
'nopaging' => true,
'date_query' => array(
array(
'after' => 'today',
'before' => 'tomorrow - 1 second',
'inclusive' => true,
),
),
);
// Replace relevant arguments in existing arguments with amended arguments.
$new_args = array_merge( $args, $arg_amendments );
// Get posts with new arguments.
$post_ids = get_posts( $new_args );
// Count results.
$count = count( $post_ids );
// Return count.
return $count;
}
```
Now you can use `wpse_287363_get_posts_today_count()` to get the number of posts made on the current date, relevant to whichever archive you're viewing.
So if you're on a category archive it will return the number of posts made today in that category. On a tag archive it will return the number of posts made today in that tag. It will even work on date archives and show the number of posts made today in a given year/month. If you're just on the blog page it will show the number of posts made today in any category or tag. It should even work with custom post type/taxonomy archives.
|
287,377 |
<p>I would like to create a blogroll page with a table where the links would be in the left table division and the description in the right division. So far, everything works... </p>
<p>Where it becomes tricky is that I would like a table for each link category. Unfortunately, the sql table links doesn't have a column link_category, it is located in taxonomy terms table. </p>
<p>I have tried many ways but I just can't get the right query. You can see my code below. It outputs the links and descriptions in a table, you can see it in action here: <a href="http://www.thebrutes.org/links/" rel="nofollow noreferrer">http://www.thebrutes.org/links/</a></p>
<p></p>
<pre><code>$links = $wpdb->get_results("SELECT * FROM $wpdb->links ORDER BY link_name ASC");
echo "<table>";
foreach ($links as $link) {
$linkurl=$link->link_url;
$linkdesc=$link->link_description;
$linkname=$link->link_name;
echo "<tr><td><a href='$linkurl' target='_blank'>$linkname</a></td>";
echo "<td>$linkdesc</td></tr>"; }
echo "</table>";
</code></pre>
<p></p>
<p>So, if anyone would know a way to create a separate table for each link category created in my bookmarks, it would be greatly appreciated.</p>
<p>Or maybe is there an easier way but I haven't figured out how to use wp_list_bookmarks to output the links and their descriptions in separate table divisions...</p>
|
[
{
"answer_id": 287567,
"author": "Chris",
"author_id": 132409,
"author_profile": "https://wordpress.stackexchange.com/users/132409",
"pm_score": 0,
"selected": false,
"text": "<p>I've found a way to output the blogroll links in a table with the categories as title, without using a custom query:</p>\n\n<pre><code>wp_list_bookmarks('categorize=1&category_before=&category_after=</table>&title_before=<h3>&title_after=</h3><table><tr><th>Link</th><th>Description</th><tr>&orderby=name&order=ASC&before=<tr><td>&after=</td></tr>&between=</td><td>&show_description=1&show_name=1');\n</code></pre>\n\n<p>I hope it'll be of some use to someone else ;-)</p>\n"
},
{
"answer_id": 287674,
"author": "Chris",
"author_id": 132409,
"author_profile": "https://wordpress.stackexchange.com/users/132409",
"pm_score": 1,
"selected": false,
"text": "<p>As suggested, here is the \"arrayed\" version:</p>\n\n<pre><code> $args = array( \n 'categorize' => 1, \n 'category_before' => '', \n 'category_after' => '</table>',\n 'title_before' => '<h3>',\n 'title_after' => '</h3><table><tr><th>Link</th><th>Description</th><tr>', \n 'orderby' => 'name', \n 'order' => 'ASC', \n 'before' => '<tr><td>', \n 'after' => '</td></tr>', \n 'between' => '</td><td>', \n 'show_description' => 1, \n 'show_name' => 1\n );\n\n wp_list_bookmarks( $args );\n</code></pre>\n\n<p>The Highlight of my answer isn't so much categorize as it is about outputing a table AFTER the category title and separating the kinl description from the link name, as showned on my page: <a href=\"http://www.thebrutes.org/links\" rel=\"nofollow noreferrer\">http://www.thebrutes.org/links</a>.</p>\n\n<p>One detail I left out is that the wp_list_bookmarks function outputs a xoxo blogroll class, which is useless and very badly named (what's next, lolol class?). For those, like me who want to get rid of it, add these lines to your style.css:</p>\n\n<pre><code>ul.xoxo.blogroll { display: none; }\n</code></pre>\n\n<p>Voilà, I hope it'll help someone. I haven't found a single answer to this question, neither here nor anywhere else.</p>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132409/"
] |
I would like to create a blogroll page with a table where the links would be in the left table division and the description in the right division. So far, everything works...
Where it becomes tricky is that I would like a table for each link category. Unfortunately, the sql table links doesn't have a column link\_category, it is located in taxonomy terms table.
I have tried many ways but I just can't get the right query. You can see my code below. It outputs the links and descriptions in a table, you can see it in action here: <http://www.thebrutes.org/links/>
```
$links = $wpdb->get_results("SELECT * FROM $wpdb->links ORDER BY link_name ASC");
echo "<table>";
foreach ($links as $link) {
$linkurl=$link->link_url;
$linkdesc=$link->link_description;
$linkname=$link->link_name;
echo "<tr><td><a href='$linkurl' target='_blank'>$linkname</a></td>";
echo "<td>$linkdesc</td></tr>"; }
echo "</table>";
```
So, if anyone would know a way to create a separate table for each link category created in my bookmarks, it would be greatly appreciated.
Or maybe is there an easier way but I haven't figured out how to use wp\_list\_bookmarks to output the links and their descriptions in separate table divisions...
|
As suggested, here is the "arrayed" version:
```
$args = array(
'categorize' => 1,
'category_before' => '',
'category_after' => '</table>',
'title_before' => '<h3>',
'title_after' => '</h3><table><tr><th>Link</th><th>Description</th><tr>',
'orderby' => 'name',
'order' => 'ASC',
'before' => '<tr><td>',
'after' => '</td></tr>',
'between' => '</td><td>',
'show_description' => 1,
'show_name' => 1
);
wp_list_bookmarks( $args );
```
The Highlight of my answer isn't so much categorize as it is about outputing a table AFTER the category title and separating the kinl description from the link name, as showned on my page: <http://www.thebrutes.org/links>.
One detail I left out is that the wp\_list\_bookmarks function outputs a xoxo blogroll class, which is useless and very badly named (what's next, lolol class?). For those, like me who want to get rid of it, add these lines to your style.css:
```
ul.xoxo.blogroll { display: none; }
```
Voilà, I hope it'll help someone. I haven't found a single answer to this question, neither here nor anywhere else.
|
287,422 |
<p>I have installed <a href="https://www.advancedcustomfields.com/" rel="nofollow noreferrer">Advanced Custom Fielts</a>, and I have created custom fields such as email, phone etc. I put those in my footer.php, and the data is displayed only on the homepage.
Can I use ACF to create global variables?
My rule for that custom field is <code>'If Post Type is equal to post';</code></p>
<p>I get that data in footer.php like this</p>
<pre><code>$phone_number = get_field('phone_number');
</code></pre>
<p>and Im displaying it like </p>
<pre><code><?php echo $phone_number; ?>
</code></pre>
<p>So basically when Im on my homepage, it is displayed correctly, when I go to other page(which has that same footer), data is not displayed.
What can I do to display it on all pages?</p>
|
[
{
"answer_id": 287426,
"author": "Narek Zakarian",
"author_id": 92573,
"author_profile": "https://wordpress.stackexchange.com/users/92573",
"pm_score": 3,
"selected": true,
"text": "<p>You Need to use <a href=\"https://wordpress.org/plugins/acf-option-pages/\" rel=\"nofollow noreferrer\">ACF Options Page</a> plugin as well.</p>\n<p><em><strong>This Plugin has been deleted from the repository. Now you can use the function without the plugin.</strong></em></p>\n<p>The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is <strong>global</strong>.</p>\n<p>Sea the plugin <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">overview</a></p>\n<p>After installing plugin you have to add the following to your <code>functions.php</code></p>\n<pre><code>if( function_exists('acf_add_options_page') ) {\n \n acf_add_options_page();\n \n}\n</code></pre>\n<p>and the "<em>Options</em>" label will be visible in your admin area.</p>\n<p>then you just need to create acf fields with the rule like <code>'If Options Page is equal to Options'</code></p>\n<p>Finally to display the field:</p>\n<pre><code>echo get_field('phone_number', 'option');\n</code></pre>\n"
},
{
"answer_id": 287432,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>That is because you're setting the field value as a post_meta value.</p>\n\n<p>To achieve what you're trying to achieve, you need to create an options page. See: <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/options-page/</a></p>\n\n<p>That will allow you to display data globally.</p>\n"
},
{
"answer_id": 287434,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>As other users mention to create global options you need to have <a href=\"https://www.advancedcustomfields.com/add-ons/options-page/\" rel=\"noreferrer\">ACF Options Page</a> add-on or <a href=\"https://www.advancedcustomfields.com/pro/\" rel=\"noreferrer\">ACF PRO</a>. This will give you possibility to create nice options page and retrive your field in standard way:</p>\n\n<pre><code>$phone_number = get_field( 'phone_number', 'option' );\n</code></pre>\n\n<p>However there is a trick you can use to retrive your fields on every page.</p>\n\n<p>If your options are working only on homepage I'm assuming you created custom fields on your homepage administration page. To retrive this fields on other pages pass your homepage ID as second argument. </p>\n\n<pre><code>$homepage_id = get_option('page_on_front');\n\n$phone_number = get_field( 'phone_number', $homepage_id );\n</code></pre>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131267/"
] |
I have installed [Advanced Custom Fielts](https://www.advancedcustomfields.com/), and I have created custom fields such as email, phone etc. I put those in my footer.php, and the data is displayed only on the homepage.
Can I use ACF to create global variables?
My rule for that custom field is `'If Post Type is equal to post';`
I get that data in footer.php like this
```
$phone_number = get_field('phone_number');
```
and Im displaying it like
```
<?php echo $phone_number; ?>
```
So basically when Im on my homepage, it is displayed correctly, when I go to other page(which has that same footer), data is not displayed.
What can I do to display it on all pages?
|
You Need to use [ACF Options Page](https://wordpress.org/plugins/acf-option-pages/) plugin as well.
***This Plugin has been deleted from the repository. Now you can use the function without the plugin.***
The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is **global**.
Sea the plugin [overview](https://www.advancedcustomfields.com/resources/options-page/)
After installing plugin you have to add the following to your `functions.php`
```
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
```
and the "*Options*" label will be visible in your admin area.
then you just need to create acf fields with the rule like `'If Options Page is equal to Options'`
Finally to display the field:
```
echo get_field('phone_number', 'option');
```
|
287,451 |
<p>I'm working on my first WooCommerce site for an e-commerce shop I'll be launching hopefully in January (I should say that I've been working with Wordpress since the very beginning, so I'm not new to WP or PHP development) but I'm struggling with how to setup a good development/production environment.</p>
<p>I've been searching for an answer to this but so far the closets I've come to an answer was that there is no "good way" to do it and require manually updating.</p>
<p>The problem is of cause that Wordpress keeps everything in the same database, from posts (and orders) to settings and meta-data.</p>
<p>Previously I've been able to make an duplicate or snapshot of my production site, overwrite my localhost, and then work from there. Confidence that my production site will not receive any new content in the meantime.<br>
But this is not very likely for an ecommerce website.</p>
<p>The files itself is not the issue, this is handled by <code>git</code> but the database is a much more difficult nut to crack.</p>
<p>I'm the developer. We have an designer / CSS wizard too, and we both work on localhost. Then, we have a storage guy and a sells guy and for them to approve and preview changes, we have an online staging environment.
And as the very last thing we, of cause, have the production environment, the actually "store".</p>
<p>I would appreciate any thoughts, ideas, links or other great advice in how others have solved this or if there is some nice structures / plugins that can help in ensure that this can be done properly.</p>
<p>Thanks</p>
|
[
{
"answer_id": 287426,
"author": "Narek Zakarian",
"author_id": 92573,
"author_profile": "https://wordpress.stackexchange.com/users/92573",
"pm_score": 3,
"selected": true,
"text": "<p>You Need to use <a href=\"https://wordpress.org/plugins/acf-option-pages/\" rel=\"nofollow noreferrer\">ACF Options Page</a> plugin as well.</p>\n<p><em><strong>This Plugin has been deleted from the repository. Now you can use the function without the plugin.</strong></em></p>\n<p>The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is <strong>global</strong>.</p>\n<p>Sea the plugin <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">overview</a></p>\n<p>After installing plugin you have to add the following to your <code>functions.php</code></p>\n<pre><code>if( function_exists('acf_add_options_page') ) {\n \n acf_add_options_page();\n \n}\n</code></pre>\n<p>and the "<em>Options</em>" label will be visible in your admin area.</p>\n<p>then you just need to create acf fields with the rule like <code>'If Options Page is equal to Options'</code></p>\n<p>Finally to display the field:</p>\n<pre><code>echo get_field('phone_number', 'option');\n</code></pre>\n"
},
{
"answer_id": 287432,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>That is because you're setting the field value as a post_meta value.</p>\n\n<p>To achieve what you're trying to achieve, you need to create an options page. See: <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/options-page/</a></p>\n\n<p>That will allow you to display data globally.</p>\n"
},
{
"answer_id": 287434,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>As other users mention to create global options you need to have <a href=\"https://www.advancedcustomfields.com/add-ons/options-page/\" rel=\"noreferrer\">ACF Options Page</a> add-on or <a href=\"https://www.advancedcustomfields.com/pro/\" rel=\"noreferrer\">ACF PRO</a>. This will give you possibility to create nice options page and retrive your field in standard way:</p>\n\n<pre><code>$phone_number = get_field( 'phone_number', 'option' );\n</code></pre>\n\n<p>However there is a trick you can use to retrive your fields on every page.</p>\n\n<p>If your options are working only on homepage I'm assuming you created custom fields on your homepage administration page. To retrive this fields on other pages pass your homepage ID as second argument. </p>\n\n<pre><code>$homepage_id = get_option('page_on_front');\n\n$phone_number = get_field( 'phone_number', $homepage_id );\n</code></pre>\n"
}
] |
2017/11/30
|
[
"https://wordpress.stackexchange.com/questions/287451",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6751/"
] |
I'm working on my first WooCommerce site for an e-commerce shop I'll be launching hopefully in January (I should say that I've been working with Wordpress since the very beginning, so I'm not new to WP or PHP development) but I'm struggling with how to setup a good development/production environment.
I've been searching for an answer to this but so far the closets I've come to an answer was that there is no "good way" to do it and require manually updating.
The problem is of cause that Wordpress keeps everything in the same database, from posts (and orders) to settings and meta-data.
Previously I've been able to make an duplicate or snapshot of my production site, overwrite my localhost, and then work from there. Confidence that my production site will not receive any new content in the meantime.
But this is not very likely for an ecommerce website.
The files itself is not the issue, this is handled by `git` but the database is a much more difficult nut to crack.
I'm the developer. We have an designer / CSS wizard too, and we both work on localhost. Then, we have a storage guy and a sells guy and for them to approve and preview changes, we have an online staging environment.
And as the very last thing we, of cause, have the production environment, the actually "store".
I would appreciate any thoughts, ideas, links or other great advice in how others have solved this or if there is some nice structures / plugins that can help in ensure that this can be done properly.
Thanks
|
You Need to use [ACF Options Page](https://wordpress.org/plugins/acf-option-pages/) plugin as well.
***This Plugin has been deleted from the repository. Now you can use the function without the plugin.***
The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is **global**.
Sea the plugin [overview](https://www.advancedcustomfields.com/resources/options-page/)
After installing plugin you have to add the following to your `functions.php`
```
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
```
and the "*Options*" label will be visible in your admin area.
then you just need to create acf fields with the rule like `'If Options Page is equal to Options'`
Finally to display the field:
```
echo get_field('phone_number', 'option');
```
|
287,476 |
<p>I created a new page for the homepage settings of my theme using <code>add_pages_page()</code>. On that page I want to use <a href="https://codex.wordpress.org/Javascript_Reference/wp.media" rel="nofollow noreferrer">wp.media</a> to let the user select one or several images from the library (or upload new ones). I thought the way to go was meta boxes but I can't get the box to display. Here's how I tried to add the meta box:</p>
<pre><code>function register_homepage_subpage() {
add_pages_page( 'Customize Homepage', 'Homepage', 'manage_options', 'my_homepage', 'my_homepage_callback' );
}
add_action( 'admin_menu', 'register_homepage_subpage' );
function my_homepage_callback() {
banner_meta_box();
}
function banner_meta_box() {
$screen_id = get_current_screen()->id;
add_meta_box("banner-meta-box", __("Banner Options", "textdomain"), "banner_meta_box_callback", $screen-id);
}
add_action( 'add_meta_boxes', 'banner_meta_box' );
function banner_meta_box_callback() {
echo "<h2>My Title</h2>"; // this doesn't display
}
</code></pre>
<p><a href="https://wordpress.stackexchange.com/a/203404/60539">This answer</a> suggests meta boxes are only for posts types which got me confused.<br>
I don't know if my "menu slug conforms to the limits of sanitize_key()" as indicated <a href="https://developer.wordpress.org/reference/functions/add_meta_box/" rel="nofollow noreferrer">here</a>.<br>
Or am I using the <a href="https://wordpress.stackexchange.com/a/110477/60539">wrong hook</a>?<br>
Thanks for reading + helping :)</p>
|
[
{
"answer_id": 287426,
"author": "Narek Zakarian",
"author_id": 92573,
"author_profile": "https://wordpress.stackexchange.com/users/92573",
"pm_score": 3,
"selected": true,
"text": "<p>You Need to use <a href=\"https://wordpress.org/plugins/acf-option-pages/\" rel=\"nofollow noreferrer\">ACF Options Page</a> plugin as well.</p>\n<p><em><strong>This Plugin has been deleted from the repository. Now you can use the function without the plugin.</strong></em></p>\n<p>The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is <strong>global</strong>.</p>\n<p>Sea the plugin <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">overview</a></p>\n<p>After installing plugin you have to add the following to your <code>functions.php</code></p>\n<pre><code>if( function_exists('acf_add_options_page') ) {\n \n acf_add_options_page();\n \n}\n</code></pre>\n<p>and the "<em>Options</em>" label will be visible in your admin area.</p>\n<p>then you just need to create acf fields with the rule like <code>'If Options Page is equal to Options'</code></p>\n<p>Finally to display the field:</p>\n<pre><code>echo get_field('phone_number', 'option');\n</code></pre>\n"
},
{
"answer_id": 287432,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>That is because you're setting the field value as a post_meta value.</p>\n\n<p>To achieve what you're trying to achieve, you need to create an options page. See: <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/options-page/</a></p>\n\n<p>That will allow you to display data globally.</p>\n"
},
{
"answer_id": 287434,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>As other users mention to create global options you need to have <a href=\"https://www.advancedcustomfields.com/add-ons/options-page/\" rel=\"noreferrer\">ACF Options Page</a> add-on or <a href=\"https://www.advancedcustomfields.com/pro/\" rel=\"noreferrer\">ACF PRO</a>. This will give you possibility to create nice options page and retrive your field in standard way:</p>\n\n<pre><code>$phone_number = get_field( 'phone_number', 'option' );\n</code></pre>\n\n<p>However there is a trick you can use to retrive your fields on every page.</p>\n\n<p>If your options are working only on homepage I'm assuming you created custom fields on your homepage administration page. To retrive this fields on other pages pass your homepage ID as second argument. </p>\n\n<pre><code>$homepage_id = get_option('page_on_front');\n\n$phone_number = get_field( 'phone_number', $homepage_id );\n</code></pre>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60539/"
] |
I created a new page for the homepage settings of my theme using `add_pages_page()`. On that page I want to use [wp.media](https://codex.wordpress.org/Javascript_Reference/wp.media) to let the user select one or several images from the library (or upload new ones). I thought the way to go was meta boxes but I can't get the box to display. Here's how I tried to add the meta box:
```
function register_homepage_subpage() {
add_pages_page( 'Customize Homepage', 'Homepage', 'manage_options', 'my_homepage', 'my_homepage_callback' );
}
add_action( 'admin_menu', 'register_homepage_subpage' );
function my_homepage_callback() {
banner_meta_box();
}
function banner_meta_box() {
$screen_id = get_current_screen()->id;
add_meta_box("banner-meta-box", __("Banner Options", "textdomain"), "banner_meta_box_callback", $screen-id);
}
add_action( 'add_meta_boxes', 'banner_meta_box' );
function banner_meta_box_callback() {
echo "<h2>My Title</h2>"; // this doesn't display
}
```
[This answer](https://wordpress.stackexchange.com/a/203404/60539) suggests meta boxes are only for posts types which got me confused.
I don't know if my "menu slug conforms to the limits of sanitize\_key()" as indicated [here](https://developer.wordpress.org/reference/functions/add_meta_box/).
Or am I using the [wrong hook](https://wordpress.stackexchange.com/a/110477/60539)?
Thanks for reading + helping :)
|
You Need to use [ACF Options Page](https://wordpress.org/plugins/acf-option-pages/) plugin as well.
***This Plugin has been deleted from the repository. Now you can use the function without the plugin.***
The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is **global**.
Sea the plugin [overview](https://www.advancedcustomfields.com/resources/options-page/)
After installing plugin you have to add the following to your `functions.php`
```
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
```
and the "*Options*" label will be visible in your admin area.
then you just need to create acf fields with the rule like `'If Options Page is equal to Options'`
Finally to display the field:
```
echo get_field('phone_number', 'option');
```
|
287,485 |
<p>I want to let users put there username in Arabic when they register a new account, I tried a lot of methods put problem still unsolved</p>
|
[
{
"answer_id": 287426,
"author": "Narek Zakarian",
"author_id": 92573,
"author_profile": "https://wordpress.stackexchange.com/users/92573",
"pm_score": 3,
"selected": true,
"text": "<p>You Need to use <a href=\"https://wordpress.org/plugins/acf-option-pages/\" rel=\"nofollow noreferrer\">ACF Options Page</a> plugin as well.</p>\n<p><em><strong>This Plugin has been deleted from the repository. Now you can use the function without the plugin.</strong></em></p>\n<p>The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is <strong>global</strong>.</p>\n<p>Sea the plugin <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">overview</a></p>\n<p>After installing plugin you have to add the following to your <code>functions.php</code></p>\n<pre><code>if( function_exists('acf_add_options_page') ) {\n \n acf_add_options_page();\n \n}\n</code></pre>\n<p>and the "<em>Options</em>" label will be visible in your admin area.</p>\n<p>then you just need to create acf fields with the rule like <code>'If Options Page is equal to Options'</code></p>\n<p>Finally to display the field:</p>\n<pre><code>echo get_field('phone_number', 'option');\n</code></pre>\n"
},
{
"answer_id": 287432,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>That is because you're setting the field value as a post_meta value.</p>\n\n<p>To achieve what you're trying to achieve, you need to create an options page. See: <a href=\"https://www.advancedcustomfields.com/resources/options-page/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/options-page/</a></p>\n\n<p>That will allow you to display data globally.</p>\n"
},
{
"answer_id": 287434,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>As other users mention to create global options you need to have <a href=\"https://www.advancedcustomfields.com/add-ons/options-page/\" rel=\"noreferrer\">ACF Options Page</a> add-on or <a href=\"https://www.advancedcustomfields.com/pro/\" rel=\"noreferrer\">ACF PRO</a>. This will give you possibility to create nice options page and retrive your field in standard way:</p>\n\n<pre><code>$phone_number = get_field( 'phone_number', 'option' );\n</code></pre>\n\n<p>However there is a trick you can use to retrive your fields on every page.</p>\n\n<p>If your options are working only on homepage I'm assuming you created custom fields on your homepage administration page. To retrive this fields on other pages pass your homepage ID as second argument. </p>\n\n<pre><code>$homepage_id = get_option('page_on_front');\n\n$phone_number = get_field( 'phone_number', $homepage_id );\n</code></pre>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287485",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132475/"
] |
I want to let users put there username in Arabic when they register a new account, I tried a lot of methods put problem still unsolved
|
You Need to use [ACF Options Page](https://wordpress.org/plugins/acf-option-pages/) plugin as well.
***This Plugin has been deleted from the repository. Now you can use the function without the plugin.***
The options page feature provides a set of functions to add extra admin pages and all data saved on an options page is **global**.
Sea the plugin [overview](https://www.advancedcustomfields.com/resources/options-page/)
After installing plugin you have to add the following to your `functions.php`
```
if( function_exists('acf_add_options_page') ) {
acf_add_options_page();
}
```
and the "*Options*" label will be visible in your admin area.
then you just need to create acf fields with the rule like `'If Options Page is equal to Options'`
Finally to display the field:
```
echo get_field('phone_number', 'option');
```
|
287,488 |
<p>I am wondering if I could change the size of one specific catalog product image. </p>
<p>I have many products with the same size (catalog images-not single product images, not even product thumbnails) and I want to change the size of a specific product, in order to be smaller than the other catalog images. </p>
<p>How can I do that?</p>
|
[
{
"answer_id": 287489,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>Without going into too much detail..</p>\n\n<pre><code>global $product;\n\nif($product->ID == '21'):\nthe_post_thumbnail('size');\nelse:\n<default code for displaying product thumb>\nendif;\n</code></pre>\n"
},
{
"answer_id": 287498,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>single_product_archive_thumbnail_size</code> filter to change which image size is used for a particular product:</p>\n\n<pre><code>function wpse_287488_product_thumbnail_size( $size ) {\n global $product;\n\n if ( $product->get_id() === 123 ) {\n $size = 'medium';\n }\n\n return $size;\n}\nadd_filter( 'single_product_archive_thumbnail_size', 'wpse_287488_product_thumbnail_size' );\n</code></pre>\n\n<p>Just replace <code>medium</code> with the registered image size you want to use. See <a href=\"https://codex.wordpress.org/Post_Thumbnails#Thumbnail_Sizes\" rel=\"nofollow noreferrer\">this codex article</a> for an overview of image sizes and how to register your own. </p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132478/"
] |
I am wondering if I could change the size of one specific catalog product image.
I have many products with the same size (catalog images-not single product images, not even product thumbnails) and I want to change the size of a specific product, in order to be smaller than the other catalog images.
How can I do that?
|
You can use the `single_product_archive_thumbnail_size` filter to change which image size is used for a particular product:
```
function wpse_287488_product_thumbnail_size( $size ) {
global $product;
if ( $product->get_id() === 123 ) {
$size = 'medium';
}
return $size;
}
add_filter( 'single_product_archive_thumbnail_size', 'wpse_287488_product_thumbnail_size' );
```
Just replace `medium` with the registered image size you want to use. See [this codex article](https://codex.wordpress.org/Post_Thumbnails#Thumbnail_Sizes) for an overview of image sizes and how to register your own.
|
287,503 |
<p>I have spent hours researching how to do this but everything I found explains it in a way that goes over my head. I'm not great with coding but I know how to Inspect element and work from there but that doesn't help me in this case.</p>
<p>I want to use a different page layout/template on products in a specified category. I am using <a href="https://woocommerce.com/" rel="nofollow noreferrer">WooCommerce</a> and I was able to use inspect element to recreate a product page the way I desired. Then I have copied the text into the custom css and it works great. However, this ends up being a Global change.</p>
<p>A majority of my product pages would benefit from having the default template rather than the custom one I made. I want to know how to add the code inside of the brackets so that the custom css (custom template) that I've added only gets applied to products in it's designated category. </p>
<p>I hope all that makes sense. Here are pictures to give you a visual example.</p>
<p><a href="https://i.stack.imgur.com/C7JuM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C7JuM.png" alt="enter image description here"></a></p>
<p>I already know what custom css I want to add to the modified product page template. I hope that designating this custom css to the specific categories is as simple as adding brackets similar to this (sorry, I'm sure it's way wrong but I see custom css that looks similar to this)</p>
<p>.product.category-2 {
custom css changes here
}</p>
<p>Thanks for taking the time to read this and I appreciate any and all help.</p>
|
[
{
"answer_id": 287506,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 0,
"selected": false,
"text": "<p>Add this to your funtions.php\n<a href=\"https://gist.github.com/thegdshop/3197540\" rel=\"nofollow noreferrer\">https://gist.github.com/thegdshop/3197540</a></p>\n\n<p>That should add the appropriate category class when on the single prlduct page.</p>\n"
},
{
"answer_id": 287544,
"author": "MarkPraschan",
"author_id": 129862,
"author_profile": "https://wordpress.stackexchange.com/users/129862",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my solution... Added the following to <code>functions.php</code> in my child theme:</p>\n\n<pre><code>add_filter( 'body_class','my_body_classes2' );\nfunction my_body_classes2( $classes ) {\n\nif ( is_product() ) {\n\n global $post;\n $terms = get_the_terms( $post->ID, 'product_cat' );\n\n foreach ($terms as $term) {\n $product_cat_id = $term->term_id;\n $classes[] = 'product-in-cat-' . $product_cat_id; \n }\n}\nreturn $classes;\n}\n</code></pre>\n\n<p>Now whenever you're viewing a single product page, an additional CSS class for each category the product is in will be added to the <code><body></code> tag.</p>\n\n<p>Then if you want to change the styling for any single product pages in category 2 or 4, you can use the following CSS:</p>\n\n<pre><code>.product-in-cat-2 , .product-in-cat-4 {\n color: #ffffff;\n}\n</code></pre>\n"
},
{
"answer_id": 303917,
"author": "TurboWeb.ro",
"author_id": 143887,
"author_profile": "https://wordpress.stackexchange.com/users/143887",
"pm_score": 0,
"selected": false,
"text": "<p>1) Install plug-in \"add costum CSS\" </p>\n\n<p>2) This will not display a box to add css by default. You need to go into the plug in (lower part of the admin bar) and there will be a question about \"enable costum CSS for following pages\" - then check the \"products\" and you will now have a box to add CSS in individual producs when you go in them through woocommerce.</p>\n\n<p>I don't know if you can do that kind of thing through this method, I needed this for removing render blocking CSS on a product page. </p>\n"
},
{
"answer_id": 304984,
"author": "Ashar Zafar",
"author_id": 131248,
"author_profile": "https://wordpress.stackexchange.com/users/131248",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Add a body class related to the product category in WooCommerce</strong>\nAdd this to your functions.php</p>\n\n<pre><code>add_filter( 'body_class', 'wc_cat_names' );\nfunction wc_cat_names( $classes ) {\n if(is_product()){\n global $post;\n $terms = get_the_terms( $post->ID, 'product_cat' );\n foreach ($terms as $term) {\n $classes[] = $term->slug;\n }\n }\n return $classes;\n}\n</code></pre>\n"
},
{
"answer_id": 346096,
"author": "Aadii Mughal",
"author_id": 146130,
"author_profile": "https://wordpress.stackexchange.com/users/146130",
"pm_score": 0,
"selected": false,
"text": "<p>i have added this code in functions.php file by going</p>\n\n<pre><code>dashboard ...>>> appearance >>> editor >>>> functions.php \n</code></pre>\n\n<p>bottom of the code pasted </p>\n\n<pre><code>add_filter( 'body_class','my_body_classes2' );\nfunction my_body_classes2( $classes ) {\n\nif ( is_product() ) {\n\n global $post;\n $terms = get_the_terms( $post->ID, 'product_cat' );\n\n foreach ($terms as $term) {\n $product_cat_id = $term->term_id;\n $classes[] = 'product-in-cat-' . $product_cat_id; \n }\n}\nreturn $classes;\n}\n</code></pre>\n\n<p>then i goes to \ndashboard ...>>> product >>>> categories >>> \nhover the mouse on edit button and id i got </p>\n\n<p>that same id i placed on single product page </p>\n\n<pre><code>.product-in-cat-(ID) {\n color: #ffffff;\n}\n</code></pre>\n\n<p>it's worked</p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287503",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132485/"
] |
I have spent hours researching how to do this but everything I found explains it in a way that goes over my head. I'm not great with coding but I know how to Inspect element and work from there but that doesn't help me in this case.
I want to use a different page layout/template on products in a specified category. I am using [WooCommerce](https://woocommerce.com/) and I was able to use inspect element to recreate a product page the way I desired. Then I have copied the text into the custom css and it works great. However, this ends up being a Global change.
A majority of my product pages would benefit from having the default template rather than the custom one I made. I want to know how to add the code inside of the brackets so that the custom css (custom template) that I've added only gets applied to products in it's designated category.
I hope all that makes sense. Here are pictures to give you a visual example.
[](https://i.stack.imgur.com/C7JuM.png)
I already know what custom css I want to add to the modified product page template. I hope that designating this custom css to the specific categories is as simple as adding brackets similar to this (sorry, I'm sure it's way wrong but I see custom css that looks similar to this)
.product.category-2 {
custom css changes here
}
Thanks for taking the time to read this and I appreciate any and all help.
|
Here's my solution... Added the following to `functions.php` in my child theme:
```
add_filter( 'body_class','my_body_classes2' );
function my_body_classes2( $classes ) {
if ( is_product() ) {
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
$classes[] = 'product-in-cat-' . $product_cat_id;
}
}
return $classes;
}
```
Now whenever you're viewing a single product page, an additional CSS class for each category the product is in will be added to the `<body>` tag.
Then if you want to change the styling for any single product pages in category 2 or 4, you can use the following CSS:
```
.product-in-cat-2 , .product-in-cat-4 {
color: #ffffff;
}
```
|
287,522 |
<p>I just can’t understand how add_image_size() and responsive images work. </p>
<p>So let’s say I have a thumbnail like <code>720×360</code>. </p>
<p>So I’m assuming I need to add the size
<code>add_image_size('post-thumbnail', 720, 320, true) //hard crop</code></p>
<p>I upload image with the dimensions of 3000×2000 to accommodate for retina screens, etc. </p>
<p>Now I’m adding it to the page with
<code>the_post_thumbail('post-thumbnail')</code> but it doesn’t build srcset at all! </p>
<p>If I’m using <code>the_post_thumbail('full')</code> it builds <code>srcset</code> but doesn’t preserve the aspect ratio. </p>
<p>So what I'm supposed to do now? </p>
<p>Do I need to add more sizes, starting from the largest? Like: </p>
<p><code>
add_image_size('post-thumbnail', 3200, 1600, true);
add_image_size('post-thumbnail-lg', 1600, 800, true);
add_image_size('post-thumbnail-sm', 1200, 600, true);
add_image_size('post-thumbnail-xs', 400, 200, true);
</code></p>
<p>If not, how would I preserve the aspect ratio?</p>
|
[
{
"answer_id": 287523,
"author": "Daniel Fonda",
"author_id": 132335,
"author_profile": "https://wordpress.stackexchange.com/users/132335",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function adjust_image_sizes_attr( $sizes, $size ) {\n $sizes = '(max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 1362px) 62vw, 840px';\n return $sizes;\n}\nadd_filter( 'wp_calculate_image_sizes', 'adjust_image_sizes_attr', 10 , 2 );\n</code></pre>\n\n<p>As outlined here:\n<a href=\"https://www.smashingmagazine.com/2015/12/responsive-images-in-wordpress-core/\" rel=\"nofollow noreferrer\">https://www.smashingmagazine.com/2015/12/responsive-images-in-wordpress-core/</a></p>\n"
},
{
"answer_id": 383195,
"author": "Glen Charles Rowell",
"author_id": 170708,
"author_profile": "https://wordpress.stackexchange.com/users/170708",
"pm_score": 2,
"selected": false,
"text": "<p>If you add the code after you have uploaded images onto pages you will also need to regenerate the images with a plugin like Regenerate Thumbnails by Alex Mills (Viper007Bond). <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n<p>I was trying to do the same thing and found many pages that offered code that didn't work so I wanted to add an update here as this page shows up when people are trying to solve the same problem.</p>\n<p>Here is some sample code that loads the different sizes depending on how large the image is. If you load a 980px width image onto the page it would have more breaks than if you load a 670px width image onto a page. The set is determined by the size you choose when putting the image on the page. Hope some people find this useful. I also found out you can add extra code right next to the return and inject other values into the sizes attribute. We don't need to do this but it's just interesting. return $sizes . " something here";</p>\n<pre><code>function adjust_image_sizes_attr($sizes,$size){\n $width = $size[0];\n if($width >= 980){\n $sizes = '\n (max-width:320px)100vw,\n (max-width:335px)100vw,\n (max-width:414px)100vw,\n (max-width:640px)100vw,\n (max-width:670px)100vw,\n (max-width:768px)100vw,\n (max-width:950px)100vw,\n (max-width:980px)980px,980px';\n }\n elseif($width >= 670){\n $sizes = '\n (max-width:320px)100vw,\n (max-width:414px)100vw,\n (max-width:670px)670px,670px';\n }\n else{\n $sizes= '(max-width:' . $width . 'px) 100vw,' . $width . 'px';}\n return $sizes;\n}\nadd_filter('wp_calculate_image_sizes', __NAMESPACE__ . '\\\\adjust_image_sizes_attr',10,2);\n</code></pre>\n<p>You can replace 100vw for sizes you wanna load if you just want a certain size.</p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] |
I just can’t understand how add\_image\_size() and responsive images work.
So let’s say I have a thumbnail like `720×360`.
So I’m assuming I need to add the size
`add_image_size('post-thumbnail', 720, 320, true) //hard crop`
I upload image with the dimensions of 3000×2000 to accommodate for retina screens, etc.
Now I’m adding it to the page with
`the_post_thumbail('post-thumbnail')` but it doesn’t build srcset at all!
If I’m using `the_post_thumbail('full')` it builds `srcset` but doesn’t preserve the aspect ratio.
So what I'm supposed to do now?
Do I need to add more sizes, starting from the largest? Like:
`add_image_size('post-thumbnail', 3200, 1600, true);
add_image_size('post-thumbnail-lg', 1600, 800, true);
add_image_size('post-thumbnail-sm', 1200, 600, true);
add_image_size('post-thumbnail-xs', 400, 200, true);`
If not, how would I preserve the aspect ratio?
|
If you add the code after you have uploaded images onto pages you will also need to regenerate the images with a plugin like Regenerate Thumbnails by Alex Mills (Viper007Bond). <https://wordpress.org/plugins/regenerate-thumbnails/>
I was trying to do the same thing and found many pages that offered code that didn't work so I wanted to add an update here as this page shows up when people are trying to solve the same problem.
Here is some sample code that loads the different sizes depending on how large the image is. If you load a 980px width image onto the page it would have more breaks than if you load a 670px width image onto a page. The set is determined by the size you choose when putting the image on the page. Hope some people find this useful. I also found out you can add extra code right next to the return and inject other values into the sizes attribute. We don't need to do this but it's just interesting. return $sizes . " something here";
```
function adjust_image_sizes_attr($sizes,$size){
$width = $size[0];
if($width >= 980){
$sizes = '
(max-width:320px)100vw,
(max-width:335px)100vw,
(max-width:414px)100vw,
(max-width:640px)100vw,
(max-width:670px)100vw,
(max-width:768px)100vw,
(max-width:950px)100vw,
(max-width:980px)980px,980px';
}
elseif($width >= 670){
$sizes = '
(max-width:320px)100vw,
(max-width:414px)100vw,
(max-width:670px)670px,670px';
}
else{
$sizes= '(max-width:' . $width . 'px) 100vw,' . $width . 'px';}
return $sizes;
}
add_filter('wp_calculate_image_sizes', __NAMESPACE__ . '\\adjust_image_sizes_attr',10,2);
```
You can replace 100vw for sizes you wanna load if you just want a certain size.
|
287,532 |
<p>I have a fresh Wordpress installation that works fine. I decide to make it work under HTTPS so I go in the General config and change the "Wordpress Address" and the "Site Adress" from <a href="http://my.website.com/blog/" rel="noreferrer">http://my.website.com/blog/</a> to <a href="https://my.website.com/blog/" rel="noreferrer">https://my.website.com/blog/</a>.</p>
<p>First, this create a redirection loop so I have to add the following lines to my wp_config.php:</p>
<pre><code>/** SSL */
define('FORCE_SSL_ADMIN', true);
// in some setups HTTP_X_FORWARDED_PROTO might contain
// a comma-separated list e.g. http,https
// so check for https existence
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
</code></pre>
<p>There, I'm able to see the blog in HTTPS as well as the login page. Once I try to login though, I get the following error: <code>Sorry, you are not allowed to access this page.</code></p>
<p>Impossible to access to the admin interface in HTTPS.</p>
<p>If I reverse the URLs (via phpMyAdmin) and remove the lines from my wp_config.php file, I can login properly. Any idea what is wrong with my installation? Is it the fact that the blog is under /blog/?</p>
<p>Thanks for your help!</p>
|
[
{
"answer_id": 287539,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 2,
"selected": false,
"text": "<p>After changing the \"Wordpress Address\" and the \"Site Adress\" to <code>https</code>, and keeping <code>FORCE_SSL_ADMIN</code> set to <code>true</code>, I would make the <code>http</code> to <code>https</code> redirects occur above the code - so you're not relying on PHP/Wordpress to do it. If running Apache do it with <code>.htaccess</code>:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]\n</code></pre>\n\n<p>If Nginx there's lots of how-to's online. If you want to limit it to just your /blog/ or subdomain, you can refine the <code>RewriteCond</code>'s.</p>\n\n<p>After that try logging in again. If you still get admin permission errors, try in Private Browsing mode to rule out a confused login cookie.</p>\n\n<p>(Also in \"Related\" sidebar, found this thread where using <code>$_SERVER['HTTPS']</code> with <code>FORCE_SSL_ADMIN</code> caused exact same issues: <a href=\"https://wordpress.stackexchange.com/questions/250240/setting-serverhttps-on-prevents-access-to-wp-admin?rq=1\">Setting $_SERVER['HTTPS']='on' prevents access to wp-admin</a> )</p>\n"
},
{
"answer_id": 307509,
"author": "TheAlbear",
"author_id": 132500,
"author_profile": "https://wordpress.stackexchange.com/users/132500",
"pm_score": 4,
"selected": false,
"text": "<p>Just a quick note, the code</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\nif ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')\n $_SERVER['HTTPS']='on';\n</code></pre>\n\n<p>need to be at the top of the config file just after the <code><php</code> or it will not work. </p>\n"
},
{
"answer_id": 320521,
"author": "Kmaj",
"author_id": 154930,
"author_profile": "https://wordpress.stackexchange.com/users/154930",
"pm_score": 1,
"selected": false,
"text": "<p>Also search wp-setting.php file for <code>define('DISALLOW_FILE_MODS',true);</code> and delete it. Non of the above solutions worked for me except this one!</p>\n"
},
{
"answer_id": 340552,
"author": "Sibi Paul",
"author_id": 170014,
"author_profile": "https://wordpress.stackexchange.com/users/170014",
"pm_score": 2,
"selected": false,
"text": "<p>This Really Worked for me in AWS, Amazon Linux 2</p>\n\n<p>WordPress LAMP + Wordpress </p>\n\n<p>Added this Code at the top of the <code>wp-config.php</code>:</p>\n\n<pre><code><?php\ndefine('FORCE_SSL_ADMIN', true);\nif ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')\n $_SERVER['HTTPS']='on';\n</code></pre>\n\n<p>Thanks</p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132511/"
] |
I have a fresh Wordpress installation that works fine. I decide to make it work under HTTPS so I go in the General config and change the "Wordpress Address" and the "Site Adress" from <http://my.website.com/blog/> to <https://my.website.com/blog/>.
First, this create a redirection loop so I have to add the following lines to my wp\_config.php:
```
/** SSL */
define('FORCE_SSL_ADMIN', true);
// in some setups HTTP_X_FORWARDED_PROTO might contain
// a comma-separated list e.g. http,https
// so check for https existence
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';
```
There, I'm able to see the blog in HTTPS as well as the login page. Once I try to login though, I get the following error: `Sorry, you are not allowed to access this page.`
Impossible to access to the admin interface in HTTPS.
If I reverse the URLs (via phpMyAdmin) and remove the lines from my wp\_config.php file, I can login properly. Any idea what is wrong with my installation? Is it the fact that the blog is under /blog/?
Thanks for your help!
|
Just a quick note, the code
```
define('FORCE_SSL_ADMIN', true);
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS']='on';
```
need to be at the top of the config file just after the `<php` or it will not work.
|
287,547 |
<p>I want to import a style only on specific site types (articles (single.php), categories (category.php) and 404 page (404.php)). I tried to use is_page() but I don't know if it works for different site types. Thank you for your help.</p>
<p><strong>Update</strong>
this is what I tried</p>
<pre><code>wp_register_style('style-narrow', '/wp-content/themes/my theme/css/style-article-narrow.css');
if ( is_singular() ) {
wp_enqueue_style('style-narrow', 'general', '1.0', 'screen');
}
</code></pre>
<p>and</p>
<pre><code>wp_register_style('style-narrow', '/wp-content/themes/my theme/css/style-article-narrow.css');
if ( is_page_template( 'category.php' ) ) {
wp_enqueue_style('style-narrow', 'general', '1.0', 'screen');
}
</code></pre>
|
[
{
"answer_id": 287548,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 1,
"selected": false,
"text": "<p><code>is_tax()</code> and <code>is_404()</code> perhaps?</p>\n\n<p><a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Conditional_Tags</a></p>\n\n<hr>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>I'm sorry my original answer was vague, to elaborate better:</p>\n\n<p>You can add conditional tags in a <code>wp_enqueue_scripts</code> hook, choosing to register and enqueue when criteria is met, like so:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'mythemes_scripts' );\nfunction mythemes_scripts() {\n\n if (is_category()) {\n wp_register_style(\n 'categoryStyles', \n get_template_directory_uri() . '/style-category.css', \n array(), // maybe the primary style.css handle here \n filemtime( get_template_directory() . '/style-category.css' )\n );\n wp_enqueue_style( 'categoryStyles');\n }\n\n if (is_404()) {\n wp_register_style(\n 'fourohfourStyles', \n get_template_directory_uri() . '/style-404.css', \n array(), // maybe the primary style.css handle here \n filemtime( get_template_directory() . '/style-404.css' )\n );\n wp_enqueue_style( 'fourohfourStyles');\n }\n\n}\n</code></pre>\n\n<p>The codex link above has many more conditional tags for situations like <code>is_archive()</code>.</p>\n\n<p>I've put <code>\"// maybe the primary style.css handle here\"</code> as doing so makes the main style sheet load before your conditional style sheets - so any CSS redefinitions are overwriting properly.</p>\n\n<p>The <code>filemtime()</code> for version numbering (instead of '1.0') will help with cache-breaking, which is valuable while trying to troubleshoot with multiple CSS includes that are presumably redefining.</p>\n\n<p>And if this code is for a plugin instead of a theme you can swap <code>get_template_directory_uri()</code>/<code>get_template_directory_uri()</code> out for <code>plugins_url()</code>/<code>plugin_dir_path()</code> respectively.</p>\n"
},
{
"answer_id": 287551,
"author": "p_0g_amm3_",
"author_id": 132533,
"author_profile": "https://wordpress.stackexchange.com/users/132533",
"pm_score": 0,
"selected": false,
"text": "<p>As mmm pointed out, I could also use wp_enqueue_style in my template file, so I created another header (header_single.php) with</p>\n\n<pre><code><?php wp_enqueue_style('style-narrow', 'general', '1.0', 'screen'); ?>\n<?php wp_head(); ?>\n</code></pre>\n\n<p>Note that the style has to be enqueued before <code>wp_head()</code> is called.</p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132533/"
] |
I want to import a style only on specific site types (articles (single.php), categories (category.php) and 404 page (404.php)). I tried to use is\_page() but I don't know if it works for different site types. Thank you for your help.
**Update**
this is what I tried
```
wp_register_style('style-narrow', '/wp-content/themes/my theme/css/style-article-narrow.css');
if ( is_singular() ) {
wp_enqueue_style('style-narrow', 'general', '1.0', 'screen');
}
```
and
```
wp_register_style('style-narrow', '/wp-content/themes/my theme/css/style-article-narrow.css');
if ( is_page_template( 'category.php' ) ) {
wp_enqueue_style('style-narrow', 'general', '1.0', 'screen');
}
```
|
`is_tax()` and `is_404()` perhaps?
<https://codex.wordpress.org/Conditional_Tags>
---
**UPDATE:**
I'm sorry my original answer was vague, to elaborate better:
You can add conditional tags in a `wp_enqueue_scripts` hook, choosing to register and enqueue when criteria is met, like so:
```
add_action( 'wp_enqueue_scripts', 'mythemes_scripts' );
function mythemes_scripts() {
if (is_category()) {
wp_register_style(
'categoryStyles',
get_template_directory_uri() . '/style-category.css',
array(), // maybe the primary style.css handle here
filemtime( get_template_directory() . '/style-category.css' )
);
wp_enqueue_style( 'categoryStyles');
}
if (is_404()) {
wp_register_style(
'fourohfourStyles',
get_template_directory_uri() . '/style-404.css',
array(), // maybe the primary style.css handle here
filemtime( get_template_directory() . '/style-404.css' )
);
wp_enqueue_style( 'fourohfourStyles');
}
}
```
The codex link above has many more conditional tags for situations like `is_archive()`.
I've put `"// maybe the primary style.css handle here"` as doing so makes the main style sheet load before your conditional style sheets - so any CSS redefinitions are overwriting properly.
The `filemtime()` for version numbering (instead of '1.0') will help with cache-breaking, which is valuable while trying to troubleshoot with multiple CSS includes that are presumably redefining.
And if this code is for a plugin instead of a theme you can swap `get_template_directory_uri()`/`get_template_directory_uri()` out for `plugins_url()`/`plugin_dir_path()` respectively.
|
287,549 |
<p>I have Set Up a Remote Database to Optimize wordpress Site Performance with MySQL on Ubuntu 16.04. I downloaded the wordpress onto my web server. When I Navigate to the public IP address associated with my web server, i get "Error establishing a database connection". </p>
<p>With wordpressdebug mode set to true, the details of the error is:</p>
<pre><code> Warning: mysqli_real_connect(): (HY000/3159): Connections using insecure
transport are prohibited while --require_secure_transport=ON. in /var/www
/html/wp-includes/wp-db.php on line 1538
</code></pre>
<p>I have tested remote connection using the remote user and I am able to connect. This means my database server is running and my remote user credentials are also correct.</p>
<p>What may be causing this and how can I resolve this?</p>
|
[
{
"answer_id": 287566,
"author": "Terungwa",
"author_id": 96667,
"author_profile": "https://wordpress.stackexchange.com/users/96667",
"pm_score": 0,
"selected": false,
"text": "<p>adding this function below to my wp-config.php solved the problem:\ndefine('DB_SSL', true);</p>\n\n<p><strong>Reference</strong>:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/7142632/wordpress-ssl-mysql-is-this-configuration-possible\">https://stackoverflow.com/questions/7142632/wordpress-ssl-mysql-is-this-configuration-possible</a></p>\n"
},
{
"answer_id": 332503,
"author": "Daniel",
"author_id": 109760,
"author_profile": "https://wordpress.stackexchange.com/users/109760",
"pm_score": 1,
"selected": false,
"text": "<p>The quickest fix would be to go to\n<code>sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf</code> and remove the:</p>\n\n<p><code>\"requiresecuretransport = on\"</code></p>\n\n<p>Then restart via:</p>\n\n<p><code>sudo systemctl restart mysql</code></p>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96667/"
] |
I have Set Up a Remote Database to Optimize wordpress Site Performance with MySQL on Ubuntu 16.04. I downloaded the wordpress onto my web server. When I Navigate to the public IP address associated with my web server, i get "Error establishing a database connection".
With wordpressdebug mode set to true, the details of the error is:
```
Warning: mysqli_real_connect(): (HY000/3159): Connections using insecure
transport are prohibited while --require_secure_transport=ON. in /var/www
/html/wp-includes/wp-db.php on line 1538
```
I have tested remote connection using the remote user and I am able to connect. This means my database server is running and my remote user credentials are also correct.
What may be causing this and how can I resolve this?
|
The quickest fix would be to go to
`sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf` and remove the:
`"requiresecuretransport = on"`
Then restart via:
`sudo systemctl restart mysql`
|
287,556 |
<p>I have a subdirectory Wordpress network with >50 sites, it's on a primary domain of <code>wordpress.example.com</code>.</p>
<p>A client, <em>johndoe</em>, within my network will (intentionally) have a back-end that includes the main site (for branding and ownership reasons):</p>
<p><code>wordpress.example.com/johndoe/wp-admin/</code></p>
<p>then via domain mapping with <a href="https://en-ca.wordpress.org/plugins/wordpress-mu-domain-mapping/" rel="nofollow noreferrer">WordPress MU Domain Mapping By Donncha O Caoimh</a>, a front-end of:</p>
<p><code>johndoe.com/</code></p>
<hr>
<p>My problem is that the login cookie associates only to <code>wordpress.example.com</code> and is completely unrelated and unaware of <code>johndoe.com</code>, so the front-end does not recognize a user is actually logged in. This yields:</p>
<ul>
<li>no user tool-bar on front-end</li>
<li>a posts "PREVIEW changes" button doesn't work</li>
<li><code>is_user_logged_in()</code> doesn't work in front-end</li>
<li>front-end page builder plugins won't work</li>
</ul>
<hr>
<p>By disabling 'remote login' I know I can make the back-end of the site <code>johndoe.com/wp-admin/</code> which would solve all aforementioned problems. However, keeping the primary domain for the back-end is crucial. In all my readings I haven't found a solution, and I've let this question sit for years. </p>
<p>I know Wordpress.com (itself powered by a Wordpress network) seems to have solved this issue. When logged into wordpress.com venturing to a random wordpress.com blog like <a href="https://longitudes.ups.com" rel="nofollow noreferrer">https://longitudes.ups.com</a> I'm able to see my .com login, and the toolbar does not appear to be an iframe or anything silly done.</p>
<p>So, my question is, if the front-end domain of a Wordpress site is different than the back-end, is there anyway to tie the login cookie to both? If the answer is "you can't" (as all my research has returned), my follow up is, well how do the folks at Automattic do it?</p>
|
[
{
"answer_id": 289248,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 0,
"selected": false,
"text": "<p>Could you check this definitions on your <code>wp-config.php</code> file?</p>\n\n<pre><code>define('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', ''); \n</code></pre>\n\n<p>And also please check your multisite definitions.</p>\n\n<pre><code>define('WP_ALLOW_MULTISITE', true);\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false);\ndefine('DOMAIN_CURRENT_SITE', 'your-domain.com');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\ndefine('SUNRISE', 'on');\n</code></pre>\n"
},
{
"answer_id": 289392,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress is deciding whether you are logged in or not by checking <code>AUTH_COOKIE</code> and <code>LOGGED_IN_COOKIE</code>. As you have noticed these cookies are set in the same, let,s say, <code>A</code> domain which your site is. Adding the same cookies to your second <code>B</code> domain would make your user logged in in two <code>A</code> and <code>B</code> domains. Of course setting cookie from domain <code>A</code> for second <code>B</code> domain would be an enormous security flaw so you must send cookie values from domain <code>A</code> to domain <code>B</code> and set these cookies in domain <code>B</code>.</p>\n\n<p>So this is what we have to do:</p>\n\n<ul>\n<li>read cookies <code>AUTH_COOKIE</code> and <code>LOGGED_IN_COOKIE</code> on domain <code>A</code></li>\n<li>send cookies <code>AUTH_COOKIE</code> and <code>LOGGED_IN_COOKIE</code> from domain <code>A</code> to domain <code>B</code></li>\n<li>set cookies <code>AUTH_COOKIE</code> and <code>LOGGED_IN_COOKIE</code> on domain <code>B</code></li>\n</ul>\n\n<p>To read cookies we have to use two filtes <code>set_auth_cookie</code> and <code>set_logged_in_cookie</code>. To set cookies on domain <code>B</code> users browser must be on site <code>B</code> so we need to redirect user from domain <code>A</code> to domain <code>B</code> with cookie values. Redirecting with <code>GET</code> params is not an option, cookies are security sensitive, we must use <code>POST</code> request. To redirect user and send cookies data with POST we can create simple html form with url pointed to domain <code>B</code>. After user is redirected we can set cookies on domain <code>B</code> and turn back user to domain <code>A</code>.</p>\n\n<p>I created working code for my implementation.</p>\n\n<pre><code>/**\n * DOMAIN A PART PLUGIN\n */\n\nclass WPSE_287556_Send_Cookies {\n\n /**\n * Domain which user have to be redirected\n *\n * @var array\n */\n private $domainB = 'example.com';\n\n /**\n * Array of cookies to send\n *\n * @var array\n */\n private $cookies = array();\n\n /**\n * WPSE_287556_Send_Cookies constructor.\n */\n public function __construct()\n {\n /**\n * Define plugin related hooks\n */\n $this->define_hooks();\n }\n\n /**\n * Save auth and logged in cookies to array\n */\n public function save_cookie( $cookie, $expire, $expiration, $user_id, $scheme, $token ) {\n\n $this->cookies[] = $data = array(\n 'cookie' => $cookie,\n 'expire' => $expire,\n 'scheme' => $scheme,\n );\n }\n\n /**\n * Display redirect post form\n *\n * We should not redirect user with cookies in get parameters because this is\n * no safe. We also can not redirect user with post parameters. We can create\n * html post form and submit it with js.\n */\n public function display_redirect_form( $redirect_to, $requested_redirect_to, $user ) {\n\n if( is_array( $this->cookies ) && !empty( $this->cookies ) ):\n\n $url = ( is_ssl() ) ? 'https://' : 'http://' . $this->domainB . '/';\n ?>\n\n <form action=\"<?php echo esc_url( $url ); ?>\" method=\"post\" style=\"display: none;\" id=\"post_redirect_form\">\n\n <input type=\"hidden\" name=\"action\" value=\"set_cookies\" >\n\n <?php foreach($this->cookies as $index => $cookie): ?>\n <input type=\"hidden\" name=\"cookies[<?php esc_attr_e( $index ); ?>][cookie]\" value=\"<?php esc_attr_e( $cookie['cookie'] ); ?>\" >\n <input type=\"hidden\" name=\"cookies[<?php esc_attr_e( $index ); ?>][expire]\" value=\"<?php esc_attr_e( $cookie['expire'] ); ?>\" >\n <input type=\"hidden\" name=\"cookies[<?php esc_attr_e( $index ); ?>][scheme]\" value=\"<?php esc_attr_e( $cookie['scheme'] ); ?>\" >\n <?php endforeach; ?>\n\n <input type=\"hidden\" name=\"redirect_to\" value=\"<?php esc_attr_e( $redirect_to ); ?>\" >\n </form>\n <script> document.getElementById('post_redirect_form').submit(); </script>\n\n <?php exit; ?>\n\n <?php endif;\n\n return $redirect_to;\n }\n\n /**\n * Define plugin related hooks\n */\n private function define_hooks() {\n\n /**\n * Save cookies hook\n */\n add_action( 'set_auth_cookie', array($this, 'save_cookie'), 10, 6 );\n add_action( 'set_logged_in_cookie', array($this, 'save_cookie'), 10, 6 );\n\n /**\n * Display redirect post form\n *\n * This filter is used to modify redirect url after login. There is no\n * better place to modify page content after user login. Additionally\n * we have access to $redirect_to url which we can use later.\n */\n add_filter('login_redirect', array( $this, 'display_redirect_form' ), 10, 3);\n }\n}\n\nnew WPSE_287556_Send_Cookies();\n\n/**\n * END OF DOMAIN A PART PLUGIN\n */\n\n/**\n * DOMAIN B PART PLUGIN\n */\n\nclass WPSE_287556_Set_Cookies {\n\n /**\n * WPSE_287556_Set_Cookies constructor.\n */\n public function __construct()\n {\n /**\n * Define plugin related hooks\n */\n $this->define_hooks();\n }\n\n /**\n * Set auth and logged in cookies\n */\n public function set_cookies() {\n\n // Check if request is \"set auth cookie\" request\n if( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['action'] ) && $_POST['action'] === 'set_cookies' ) {\n\n $args = array(\n 'redirect_to' => FILTER_SANITIZE_URL,\n 'cookies' => array(\n 'filter' => FILTER_SANITIZE_STRING,\n 'flags' => FILTER_REQUIRE_ARRAY,\n ),\n );\n\n // Read and filter all post params\n $post = filter_input_array(INPUT_POST, $args);\n\n $redirect_to = $post['redirect_to'];\n $cookies = $post['cookies'];\n\n foreach( $cookies as $cookie_params ){\n\n $scheme = $cookie_params['scheme'];\n $cookie = $cookie_params['cookie'];\n $expire = (int) $cookie_params['expire'];\n\n // Decide which cookie to set\n switch( $scheme ) {\n\n case 'logged_in':\n\n // Set logged in cookie, most of the code is from wp_set_auth_cookie function\n setcookie( LOGGED_IN_COOKIE, $cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);\n\n if ( COOKIEPATH != SITECOOKIEPATH )\n setcookie(LOGGED_IN_COOKIE, $cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);\n\n break;\n\n case 'secure_auth':\n case 'auth':\n\n // Set auth cookie, most of the code is from wp_set_auth_cookie function\n if ( $scheme === 'secure_auth' ) {\n $auth_cookie_name = SECURE_AUTH_COOKIE;\n } else {\n $auth_cookie_name = AUTH_COOKIE;\n }\n\n setcookie($auth_cookie_name, $cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);\n setcookie($auth_cookie_name, $cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);\n\n break;\n }\n }\n\n // Redirect user to previous site\n header( 'Location: ' . esc_url( $redirect_to ) );\n exit;\n }\n }\n\n /**\n * Define plugin related hooks\n */\n private function define_hooks() {\n\n /**\n * Set cookies from request\n */\n add_action( 'init', array($this, 'set_cookies'));\n }\n}\n\nnew WPSE_287556_Set_Cookies();\n\n/**\n * END OF DOMAIN B PART PLUGIN\n */\n</code></pre>\n"
}
] |
2017/12/01
|
[
"https://wordpress.stackexchange.com/questions/287556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132362/"
] |
I have a subdirectory Wordpress network with >50 sites, it's on a primary domain of `wordpress.example.com`.
A client, *johndoe*, within my network will (intentionally) have a back-end that includes the main site (for branding and ownership reasons):
`wordpress.example.com/johndoe/wp-admin/`
then via domain mapping with [WordPress MU Domain Mapping By Donncha O Caoimh](https://en-ca.wordpress.org/plugins/wordpress-mu-domain-mapping/), a front-end of:
`johndoe.com/`
---
My problem is that the login cookie associates only to `wordpress.example.com` and is completely unrelated and unaware of `johndoe.com`, so the front-end does not recognize a user is actually logged in. This yields:
* no user tool-bar on front-end
* a posts "PREVIEW changes" button doesn't work
* `is_user_logged_in()` doesn't work in front-end
* front-end page builder plugins won't work
---
By disabling 'remote login' I know I can make the back-end of the site `johndoe.com/wp-admin/` which would solve all aforementioned problems. However, keeping the primary domain for the back-end is crucial. In all my readings I haven't found a solution, and I've let this question sit for years.
I know Wordpress.com (itself powered by a Wordpress network) seems to have solved this issue. When logged into wordpress.com venturing to a random wordpress.com blog like <https://longitudes.ups.com> I'm able to see my .com login, and the toolbar does not appear to be an iframe or anything silly done.
So, my question is, if the front-end domain of a Wordpress site is different than the back-end, is there anyway to tie the login cookie to both? If the answer is "you can't" (as all my research has returned), my follow up is, well how do the folks at Automattic do it?
|
WordPress is deciding whether you are logged in or not by checking `AUTH_COOKIE` and `LOGGED_IN_COOKIE`. As you have noticed these cookies are set in the same, let,s say, `A` domain which your site is. Adding the same cookies to your second `B` domain would make your user logged in in two `A` and `B` domains. Of course setting cookie from domain `A` for second `B` domain would be an enormous security flaw so you must send cookie values from domain `A` to domain `B` and set these cookies in domain `B`.
So this is what we have to do:
* read cookies `AUTH_COOKIE` and `LOGGED_IN_COOKIE` on domain `A`
* send cookies `AUTH_COOKIE` and `LOGGED_IN_COOKIE` from domain `A` to domain `B`
* set cookies `AUTH_COOKIE` and `LOGGED_IN_COOKIE` on domain `B`
To read cookies we have to use two filtes `set_auth_cookie` and `set_logged_in_cookie`. To set cookies on domain `B` users browser must be on site `B` so we need to redirect user from domain `A` to domain `B` with cookie values. Redirecting with `GET` params is not an option, cookies are security sensitive, we must use `POST` request. To redirect user and send cookies data with POST we can create simple html form with url pointed to domain `B`. After user is redirected we can set cookies on domain `B` and turn back user to domain `A`.
I created working code for my implementation.
```
/**
* DOMAIN A PART PLUGIN
*/
class WPSE_287556_Send_Cookies {
/**
* Domain which user have to be redirected
*
* @var array
*/
private $domainB = 'example.com';
/**
* Array of cookies to send
*
* @var array
*/
private $cookies = array();
/**
* WPSE_287556_Send_Cookies constructor.
*/
public function __construct()
{
/**
* Define plugin related hooks
*/
$this->define_hooks();
}
/**
* Save auth and logged in cookies to array
*/
public function save_cookie( $cookie, $expire, $expiration, $user_id, $scheme, $token ) {
$this->cookies[] = $data = array(
'cookie' => $cookie,
'expire' => $expire,
'scheme' => $scheme,
);
}
/**
* Display redirect post form
*
* We should not redirect user with cookies in get parameters because this is
* no safe. We also can not redirect user with post parameters. We can create
* html post form and submit it with js.
*/
public function display_redirect_form( $redirect_to, $requested_redirect_to, $user ) {
if( is_array( $this->cookies ) && !empty( $this->cookies ) ):
$url = ( is_ssl() ) ? 'https://' : 'http://' . $this->domainB . '/';
?>
<form action="<?php echo esc_url( $url ); ?>" method="post" style="display: none;" id="post_redirect_form">
<input type="hidden" name="action" value="set_cookies" >
<?php foreach($this->cookies as $index => $cookie): ?>
<input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][cookie]" value="<?php esc_attr_e( $cookie['cookie'] ); ?>" >
<input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][expire]" value="<?php esc_attr_e( $cookie['expire'] ); ?>" >
<input type="hidden" name="cookies[<?php esc_attr_e( $index ); ?>][scheme]" value="<?php esc_attr_e( $cookie['scheme'] ); ?>" >
<?php endforeach; ?>
<input type="hidden" name="redirect_to" value="<?php esc_attr_e( $redirect_to ); ?>" >
</form>
<script> document.getElementById('post_redirect_form').submit(); </script>
<?php exit; ?>
<?php endif;
return $redirect_to;
}
/**
* Define plugin related hooks
*/
private function define_hooks() {
/**
* Save cookies hook
*/
add_action( 'set_auth_cookie', array($this, 'save_cookie'), 10, 6 );
add_action( 'set_logged_in_cookie', array($this, 'save_cookie'), 10, 6 );
/**
* Display redirect post form
*
* This filter is used to modify redirect url after login. There is no
* better place to modify page content after user login. Additionally
* we have access to $redirect_to url which we can use later.
*/
add_filter('login_redirect', array( $this, 'display_redirect_form' ), 10, 3);
}
}
new WPSE_287556_Send_Cookies();
/**
* END OF DOMAIN A PART PLUGIN
*/
/**
* DOMAIN B PART PLUGIN
*/
class WPSE_287556_Set_Cookies {
/**
* WPSE_287556_Set_Cookies constructor.
*/
public function __construct()
{
/**
* Define plugin related hooks
*/
$this->define_hooks();
}
/**
* Set auth and logged in cookies
*/
public function set_cookies() {
// Check if request is "set auth cookie" request
if( $_SERVER['REQUEST_METHOD'] === 'POST' && isset( $_POST['action'] ) && $_POST['action'] === 'set_cookies' ) {
$args = array(
'redirect_to' => FILTER_SANITIZE_URL,
'cookies' => array(
'filter' => FILTER_SANITIZE_STRING,
'flags' => FILTER_REQUIRE_ARRAY,
),
);
// Read and filter all post params
$post = filter_input_array(INPUT_POST, $args);
$redirect_to = $post['redirect_to'];
$cookies = $post['cookies'];
foreach( $cookies as $cookie_params ){
$scheme = $cookie_params['scheme'];
$cookie = $cookie_params['cookie'];
$expire = (int) $cookie_params['expire'];
// Decide which cookie to set
switch( $scheme ) {
case 'logged_in':
// Set logged in cookie, most of the code is from wp_set_auth_cookie function
setcookie( LOGGED_IN_COOKIE, $cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
if ( COOKIEPATH != SITECOOKIEPATH )
setcookie(LOGGED_IN_COOKIE, $cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
break;
case 'secure_auth':
case 'auth':
// Set auth cookie, most of the code is from wp_set_auth_cookie function
if ( $scheme === 'secure_auth' ) {
$auth_cookie_name = SECURE_AUTH_COOKIE;
} else {
$auth_cookie_name = AUTH_COOKIE;
}
setcookie($auth_cookie_name, $cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);
setcookie($auth_cookie_name, $cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, is_ssl(), true);
break;
}
}
// Redirect user to previous site
header( 'Location: ' . esc_url( $redirect_to ) );
exit;
}
}
/**
* Define plugin related hooks
*/
private function define_hooks() {
/**
* Set cookies from request
*/
add_action( 'init', array($this, 'set_cookies'));
}
}
new WPSE_287556_Set_Cookies();
/**
* END OF DOMAIN B PART PLUGIN
*/
```
|
287,598 |
<p>I think i may be getting a little confused, but I have a list and a select button on each line. When the user clicks the button a modal shows up and I am trying to simple get an image (with a post_id) to display.</p>
<p>So in PHP I have this:</p>
<pre><code><img id="changeImage"src="
<?php
echo $v[0]->user_image_id ?
wp_get_attachment_image_src( $v[0]->user_image_id,
array( 'width' => 75, 'height' => 75 ))[0] :
wp_get_attachment_url( 259 ); ?>" style="width: 75px; height: 75px"/>
</code></pre>
<p>This is part of the list, so each picture (avatar) is shown. Then a button is clicked and I already have the <code>post_id</code> with this code:</p>
<pre><code>$('.selectedBtn').on('click', function (e) {
e.preventDefault();
var elm = $(this);
var data;
var dataArray = JSON.parse(sessionStorage.getItem('dataArray'));
$.each(dataArray, function(k, v) {
if(parseInt(v[0].wyol_list_id) === elm.data('wd')) {
data = v[0];
console.log(data);
$('#wd_request_shoppers_name').text(v[0].user_name);
$('#wd_request_store').text(v[0].wd_store);
var imgid = v[0].user_image_id ? v[0].user_image_id : 259;
console.log(wp.media());
// USAGE:
preloadAttachment(imgid, function (attachment) {
console.log(attachment.get('url'));
console.log(wp.media.attachment(imgid).get('url')); // this also works
});
$('#wd_request_shoppers_image').prop('src', wp.media.attachment(imgid).get('url'));
v[0].instructions ? $('#wd_request_shoppers_detail').text(v[0].instructions) : '';
$('#exampleModal1').foundation('open');
}
});
//console.log(elm.data('wd'));
});
$('#closeModal').on('click', function () {
$('#exampleModal1').foundation('close');
});
});
</code></pre>
<p>But all I get is this console.log error:</p>
<p>(index):352 Uncaught TypeError: Cannot read property 'attachment' of undefined</p>
<p>On this line:
352 if (wp.media.attachment(ID).get('url')) {</p>
<p>So has WP not got the ability to grab a url in WP?</p>
<p>Thanks in advance</p>
<p>Addy</p>
|
[
{
"answer_id": 288000,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As per my understanding I can suggest you that you can probaly use something like font-awesome. This will help you to display a image sort of thing using simple CSS class. </p>\n\n<p>So you may please check my solution and let me know your views over it.</p>\n"
},
{
"answer_id": 288291,
"author": "Moshe Harush",
"author_id": 119573,
"author_profile": "https://wordpress.stackexchange.com/users/119573",
"pm_score": 1,
"selected": false,
"text": "<p>You can add filter for <code>widget_title</code> hook.</p>\n\n<p>Or change the <code>$instance['title']</code> on update.</p>\n"
},
{
"answer_id": 288314,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 0,
"selected": false,
"text": "<p>Let me describe every situation.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IaNmY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IaNmY.png\" alt=\"The widgets\"></a></p>\n\n<ol>\n<li>If you would like to change \"Search\" on the above screenshot, I should disappoint you, you can look in /wp-admin/includes/widgets.php (line 232) and in any widget class (I opened /wp-includes/widgets/class-wp-widget-search.php) and you will find out that there are no filter hooks for it. It could be changed only in your custom widgets.</li>\n</ol>\n\n<p>On my custom widget I change it in this part of the widget class code:</p>\n\n<pre><code> function __construct() {\n parent::__construct(\n 'misha_widget', \n 'Widget title', // here it is\n array( 'description' => 'Widget description' )\n );\n }\n</code></pre>\n\n<ol start=\"2\">\n<li><p>If you would like to change \"My search\" on widget in admin area, JavaScript is good enough way to do it because WordPress also do it with JS. The widget_title hook will be applied only for website appearance not for admin area or customizer:</p>\n\n<pre><code>add_filter('widget_title', 'misha_change_title1', 10, 3 );\nfunction misha_change_title1( $title, $instance, $id ){\n if( $id == 'search' ) {\n return ''. $title;\n }\n return $title;\n}\n</code></pre></li>\n</ol>\n\n<p>What about customizer, you can find the instruction how to run custom JS code here <a href=\"https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File</a></p>\n"
}
] |
2017/12/02
|
[
"https://wordpress.stackexchange.com/questions/287598",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131139/"
] |
I think i may be getting a little confused, but I have a list and a select button on each line. When the user clicks the button a modal shows up and I am trying to simple get an image (with a post\_id) to display.
So in PHP I have this:
```
<img id="changeImage"src="
<?php
echo $v[0]->user_image_id ?
wp_get_attachment_image_src( $v[0]->user_image_id,
array( 'width' => 75, 'height' => 75 ))[0] :
wp_get_attachment_url( 259 ); ?>" style="width: 75px; height: 75px"/>
```
This is part of the list, so each picture (avatar) is shown. Then a button is clicked and I already have the `post_id` with this code:
```
$('.selectedBtn').on('click', function (e) {
e.preventDefault();
var elm = $(this);
var data;
var dataArray = JSON.parse(sessionStorage.getItem('dataArray'));
$.each(dataArray, function(k, v) {
if(parseInt(v[0].wyol_list_id) === elm.data('wd')) {
data = v[0];
console.log(data);
$('#wd_request_shoppers_name').text(v[0].user_name);
$('#wd_request_store').text(v[0].wd_store);
var imgid = v[0].user_image_id ? v[0].user_image_id : 259;
console.log(wp.media());
// USAGE:
preloadAttachment(imgid, function (attachment) {
console.log(attachment.get('url'));
console.log(wp.media.attachment(imgid).get('url')); // this also works
});
$('#wd_request_shoppers_image').prop('src', wp.media.attachment(imgid).get('url'));
v[0].instructions ? $('#wd_request_shoppers_detail').text(v[0].instructions) : '';
$('#exampleModal1').foundation('open');
}
});
//console.log(elm.data('wd'));
});
$('#closeModal').on('click', function () {
$('#exampleModal1').foundation('close');
});
});
```
But all I get is this console.log error:
(index):352 Uncaught TypeError: Cannot read property 'attachment' of undefined
On this line:
352 if (wp.media.attachment(ID).get('url')) {
So has WP not got the ability to grab a url in WP?
Thanks in advance
Addy
|
You can add filter for `widget_title` hook.
Or change the `$instance['title']` on update.
|
287,658 |
<p>I'm having a difficult time trying to update the <code>flamingo_inbound</code> post author after insert.</p>
<p>Basically, I have a hidden field in <code>CTF7</code> for the company name that is being sent over and correctly stored in the db. That field corresponds to a particular company page.</p>
<p>Here's my code so far.</p>
<pre>
function my_update_flamingo_inbound_author($post){
$post_type = get_post_type($post);
$post_id = $post->ID;
if($post_type == 'flamingo_inbound') {
$company_name = get_post_meta($post_id, '_field_company-name', true);
if($company_name)
{
$company_post = get_page_by_title($company_name, 'OBJECT', 'company');
if($company_post)
{
$post_author = $company_post->post_author;
$post->post_author = $post_author;
wp_update_post($post);
}
}
}
}
add_action( 'new_to_publish', 'my_update_flamingo_inbound_author', 10);
</pre>
|
[
{
"answer_id": 288000,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As per my understanding I can suggest you that you can probaly use something like font-awesome. This will help you to display a image sort of thing using simple CSS class. </p>\n\n<p>So you may please check my solution and let me know your views over it.</p>\n"
},
{
"answer_id": 288291,
"author": "Moshe Harush",
"author_id": 119573,
"author_profile": "https://wordpress.stackexchange.com/users/119573",
"pm_score": 1,
"selected": false,
"text": "<p>You can add filter for <code>widget_title</code> hook.</p>\n\n<p>Or change the <code>$instance['title']</code> on update.</p>\n"
},
{
"answer_id": 288314,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": 0,
"selected": false,
"text": "<p>Let me describe every situation.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IaNmY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IaNmY.png\" alt=\"The widgets\"></a></p>\n\n<ol>\n<li>If you would like to change \"Search\" on the above screenshot, I should disappoint you, you can look in /wp-admin/includes/widgets.php (line 232) and in any widget class (I opened /wp-includes/widgets/class-wp-widget-search.php) and you will find out that there are no filter hooks for it. It could be changed only in your custom widgets.</li>\n</ol>\n\n<p>On my custom widget I change it in this part of the widget class code:</p>\n\n<pre><code> function __construct() {\n parent::__construct(\n 'misha_widget', \n 'Widget title', // here it is\n array( 'description' => 'Widget description' )\n );\n }\n</code></pre>\n\n<ol start=\"2\">\n<li><p>If you would like to change \"My search\" on widget in admin area, JavaScript is good enough way to do it because WordPress also do it with JS. The widget_title hook will be applied only for website appearance not for admin area or customizer:</p>\n\n<pre><code>add_filter('widget_title', 'misha_change_title1', 10, 3 );\nfunction misha_change_title1( $title, $instance, $id ){\n if( $id == 'search' ) {\n return ''. $title;\n }\n return $title;\n}\n</code></pre></li>\n</ol>\n\n<p>What about customizer, you can find the instruction how to run custom JS code here <a href=\"https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Theme_Customization_API#Step_2:_Create_a_JavaScript_File</a></p>\n"
}
] |
2017/12/04
|
[
"https://wordpress.stackexchange.com/questions/287658",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132087/"
] |
I'm having a difficult time trying to update the `flamingo_inbound` post author after insert.
Basically, I have a hidden field in `CTF7` for the company name that is being sent over and correctly stored in the db. That field corresponds to a particular company page.
Here's my code so far.
```
function my_update_flamingo_inbound_author($post){
$post_type = get_post_type($post);
$post_id = $post->ID;
if($post_type == 'flamingo_inbound') {
$company_name = get_post_meta($post_id, '_field_company-name', true);
if($company_name)
{
$company_post = get_page_by_title($company_name, 'OBJECT', 'company');
if($company_post)
{
$post_author = $company_post->post_author;
$post->post_author = $post_author;
wp_update_post($post);
}
}
}
}
add_action( 'new_to_publish', 'my_update_flamingo_inbound_author', 10);
```
|
You can add filter for `widget_title` hook.
Or change the `$instance['title']` on update.
|
287,662 |
<p>I see the following string when I print my prepared query:</p>
<pre><code>"SELECT p.ID, COALESCE(w.value,Display_name) value, p.post_title, p.post_date, p.post_content,p.post_author,user_login FROM wp_posts p INNER JOIN wp_users a ON a.ID = p.post_author LEFT JOIN wp_bp_xprofile_data w ON w.user_id = a.ID WHERE post_type = 'reply' and post_parent = 53592568 and p.ID > 53592614 AND TIMEDIFF( '2017-12-04 06:14:58', post_date ) < '00:00:15' AND post_content is not null ORDER BY post_date ASC LIMIT 0 , 5"
</code></pre>
<p>It seems to return fine when I run it through the SQL client:
<a href="https://i.stack.imgur.com/fNLTu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fNLTu.jpg" alt="mySQL client"></a></p>
<p>But it's not returning when I try to run with the <code>wpdb->get_results</code> or <code>wpdb->query</code> function in my wordpress template.</p>
<p>Here's my code:</p>
<pre><code>global $wpdb;
$reply_id = $_REQUEST["id"];
$postId = $_REQUEST["post_id"];
$data = date("Y-m-d H:i:sa");
$dataStr = str_replace("am","",str_replace("pm","",$data));
$mysqli_query = "SELECT p.ID, COALESCE(w.value,Display_name) value, p.post_title, p.post_date, p.post_content,p.post_author,user_login ";
$mysqli_query .= " FROM wp_posts p ";
$mysqli_query .= " INNER JOIN wp_users a ON a.ID = p.post_author ";
$mysqli_query .= " LEFT JOIN wp_bp_xprofile_data w ON w.user_id = a.ID ";
$mysqli_query .= " WHERE post_type = 'reply' ";
$mysqli_query .= " and post_parent = %d ";
$mysqli_query .= " and p.ID > %d ";
$mysqli_query .= " AND TIMEDIFF( '%s', post_date ) < '00:00:15' ";
$mysqli_query .= " AND post_content is not null ";
$mysqli_query .= " ORDER BY post_date ASC ";
$mysqli_query .= " LIMIT 0 , 5";
$reply_query = $wpdb->prepare($mysqli_query, $postId, $reply_id, $dataStr);
$results = $wpdb->get_results( $reply_query );
var_dump($results);
</code></pre>
<p>Here's what <code>var_dump</code> displays for me:</p>
<pre><code>array(0) { }
</code></pre>
<p>Can anybody help me to figure out whats wrong with this code?</p>
<p>Thank you</p>
|
[
{
"answer_id": 287667,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>Don't put single quotes around placeholders, they are added automatically. Turn '%s' into just %s.</p>\n"
},
{
"answer_id": 287692,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 1,
"selected": true,
"text": "<p>There are view issues with the query:</p>\n\n<ul>\n<li>First what the @janh wrote. </li>\n<li>Second why you removing the am/pm when\nyou could easily use the <code>date(\"Y-m-d H:i:s\");</code> </li>\n<li>Third, there is this\nlittle helper for the database table prefixes <code>$wpdb->prefix</code></li>\n<li>Users table the column name is <code>display_name</code></li>\n<li>Also when you make aliases is a good rule to stick with them through the query even if there are not multiple columns with the same name.</li>\n</ul>\n\n<p>For example without counting the <code>bp_xprofile_data</code> table that I mocked:</p>\n\n<pre><code>$reply_id = $_REQUEST[\"id\"];\n$postId = $_REQUEST[\"post_id\"];\n$data = date(\"Y-m-d H:i:s\");\n$mysqli_query = \"SELECT p.ID, COALESCE(w.value,a.display_name) value, p.post_title, p.post_date, p.post_content, p.post_author, a.user_login \";\n$mysqli_query .= \" FROM {$wpdb->prefix}posts p \";\n$mysqli_query .= \" INNER JOIN {$wpdb->prefix}users a ON a.ID = p.post_author \";\n$mysqli_query .= \" LEFT JOIN {$wpdb->prefix}bp_xprofile_data w ON w.user_id = a.ID \";\n$mysqli_query .= \" WHERE p.post_type = 'reply' \";\n$mysqli_query .= \" AND p.post_parent = %d \";\n$mysqli_query .= \" AND p.ID > %d \";\n$mysqli_query .= \" AND TIMEDIFF( %s, p.post_date ) < '00:00:15' \";\n$mysqli_query .= \" AND p.post_content IS NOT NULL \";\n$mysqli_query .= \" ORDER BY p.post_date ASC \";\n$mysqli_query .= \" LIMIT 0 , 5\";\n\n$reply_query = $wpdb->prepare($mysqli_query, $postId, $reply_id, $data);\n\n$results = $wpdb->get_results( $reply_query );\n</code></pre>\n"
}
] |
2017/12/04
|
[
"https://wordpress.stackexchange.com/questions/287662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132641/"
] |
I see the following string when I print my prepared query:
```
"SELECT p.ID, COALESCE(w.value,Display_name) value, p.post_title, p.post_date, p.post_content,p.post_author,user_login FROM wp_posts p INNER JOIN wp_users a ON a.ID = p.post_author LEFT JOIN wp_bp_xprofile_data w ON w.user_id = a.ID WHERE post_type = 'reply' and post_parent = 53592568 and p.ID > 53592614 AND TIMEDIFF( '2017-12-04 06:14:58', post_date ) < '00:00:15' AND post_content is not null ORDER BY post_date ASC LIMIT 0 , 5"
```
It seems to return fine when I run it through the SQL client:
[](https://i.stack.imgur.com/fNLTu.jpg)
But it's not returning when I try to run with the `wpdb->get_results` or `wpdb->query` function in my wordpress template.
Here's my code:
```
global $wpdb;
$reply_id = $_REQUEST["id"];
$postId = $_REQUEST["post_id"];
$data = date("Y-m-d H:i:sa");
$dataStr = str_replace("am","",str_replace("pm","",$data));
$mysqli_query = "SELECT p.ID, COALESCE(w.value,Display_name) value, p.post_title, p.post_date, p.post_content,p.post_author,user_login ";
$mysqli_query .= " FROM wp_posts p ";
$mysqli_query .= " INNER JOIN wp_users a ON a.ID = p.post_author ";
$mysqli_query .= " LEFT JOIN wp_bp_xprofile_data w ON w.user_id = a.ID ";
$mysqli_query .= " WHERE post_type = 'reply' ";
$mysqli_query .= " and post_parent = %d ";
$mysqli_query .= " and p.ID > %d ";
$mysqli_query .= " AND TIMEDIFF( '%s', post_date ) < '00:00:15' ";
$mysqli_query .= " AND post_content is not null ";
$mysqli_query .= " ORDER BY post_date ASC ";
$mysqli_query .= " LIMIT 0 , 5";
$reply_query = $wpdb->prepare($mysqli_query, $postId, $reply_id, $dataStr);
$results = $wpdb->get_results( $reply_query );
var_dump($results);
```
Here's what `var_dump` displays for me:
```
array(0) { }
```
Can anybody help me to figure out whats wrong with this code?
Thank you
|
There are view issues with the query:
* First what the @janh wrote.
* Second why you removing the am/pm when
you could easily use the `date("Y-m-d H:i:s");`
* Third, there is this
little helper for the database table prefixes `$wpdb->prefix`
* Users table the column name is `display_name`
* Also when you make aliases is a good rule to stick with them through the query even if there are not multiple columns with the same name.
For example without counting the `bp_xprofile_data` table that I mocked:
```
$reply_id = $_REQUEST["id"];
$postId = $_REQUEST["post_id"];
$data = date("Y-m-d H:i:s");
$mysqli_query = "SELECT p.ID, COALESCE(w.value,a.display_name) value, p.post_title, p.post_date, p.post_content, p.post_author, a.user_login ";
$mysqli_query .= " FROM {$wpdb->prefix}posts p ";
$mysqli_query .= " INNER JOIN {$wpdb->prefix}users a ON a.ID = p.post_author ";
$mysqli_query .= " LEFT JOIN {$wpdb->prefix}bp_xprofile_data w ON w.user_id = a.ID ";
$mysqli_query .= " WHERE p.post_type = 'reply' ";
$mysqli_query .= " AND p.post_parent = %d ";
$mysqli_query .= " AND p.ID > %d ";
$mysqli_query .= " AND TIMEDIFF( %s, p.post_date ) < '00:00:15' ";
$mysqli_query .= " AND p.post_content IS NOT NULL ";
$mysqli_query .= " ORDER BY p.post_date ASC ";
$mysqli_query .= " LIMIT 0 , 5";
$reply_query = $wpdb->prepare($mysqli_query, $postId, $reply_id, $data);
$results = $wpdb->get_results( $reply_query );
```
|
287,665 |
<p>my initial <code>functions.php</code> is looks like this</p>
<pre><code><?php
/**
* SKT Charity functions and definitions
*
* @package SKT Charity
*/
global $content_width;
if ( ! isset( $content_width ) )
$content_width = 640; /* pixels */
// Set the word limit of post content
function skt_charity_content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
return $content;
}
/**
* Set the content width based on the theme's design and stylesheet.
*/
if ( ! function_exists( 'skt_charity_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which runs
* before the init hook. The init hook is too late for some features, such as indicating
* support post thumbnails.
*/
function skt_charity_setup() {
load_theme_textdomain( 'skt-charity', get_template_directory() . '/languages' );
add_theme_support( 'automatic-feed-links' );
add_theme_support('woocommerce');
add_theme_support( 'post-thumbnails' );
add_theme_support( 'custom-header', array( 'header-text' => false ) );
add_theme_support( 'title-tag' );
add_theme_support( 'custom-logo', array(
'height' => 350,
'width' => 150,
'flex-height' => true,
) );
add_image_size('skt-charity-homepage-thumb',240,145,true);
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'skt-charity' ),
) );
add_theme_support( 'custom-background', array(
'default-color' => 'ffffff'
) );
add_editor_style( 'editor-style.css' );
}
endif; // skt_charity_setup
add_action( 'after_setup_theme', 'skt_charity_setup' );
function skt_charity_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar', 'skt-charity' ),
'description' => __( 'Appears on blog page sidebar', 'skt-charity' ),
'id' => 'sidebar-1',
'before_widget' => '',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3><aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
) );
register_sidebar( array(
'name' => __( 'Header Left Widget', 'skt-charity' ),
'description' => __( 'Appears on left site of header', 'skt-charity' ),
'id' => 'header-info-left',
'before_widget' => '<div class="headerinfo">',
'after_widget' => '</div>',
'before_title' => '<h3 style="display:none">',
'after_title' => '</h3>',
) );
register_sidebar( array(
'name' => __( 'Header Right Widget', 'skt-charity' ),
'description' => __( 'Appears on right site of header', 'skt-charity' ),
'id' => 'header-info-right',
'before_widget' => '<div class="headerinfo">',
'after_widget' => '</div>',
'before_title' => '<h3 style="display:none">',
'after_title' => '</h3>',
) );
}
add_action( 'widgets_init', 'skt_charity_widgets_init' );
function skt_charity_font_url(){
$font_url = '';
/* Translators: If there are any character that are not
* supported by Roboto, trsnalate this to off, do not
* translate into your own language.
*/
$roboto = _x('on','roboto:on or off','skt-charity');
/* Translators: If there has any character that are not supported
* by Scada, translate this to off, do not translate
* into your own language.
*/
$scada = _x('on','Scada:on or off','skt-charity');
if('off' !== $roboto ){
$font_family = array();
if('off' !== $roboto){
$font_family[] = 'Roboto:300,400,600,700,800,900';
}
$query_args = array(
'family' => urlencode(implode('|',$font_family)),
);
$font_url = add_query_arg($query_args,'//fonts.googleapis.com/css');
}
return $font_url;
}
function skt_charity_scripts() {
wp_enqueue_style('skt-charity-font', skt_charity_font_url(), array());
wp_enqueue_style( 'skt-charity-basic-style', get_stylesheet_uri() );
wp_enqueue_style( 'skt-charity-editor-style', get_template_directory_uri().'/editor-style.css' );
wp_enqueue_style( 'nivoslider-style', get_template_directory_uri().'/css/nivo-slider.css' );
wp_enqueue_style( 'skt-charity-main-style', get_template_directory_uri().'/css/responsive.css' );
wp_enqueue_style( 'skt-charity-base-style', get_template_directory_uri().'/css/style_base.css' );
wp_enqueue_script( 'skt-charity-nivo-script', get_template_directory_uri() . '/js/jquery.nivo.slider.js', array('jquery') );
wp_enqueue_script( 'skt-charity-custom_js', get_template_directory_uri() . '/js/custom.js' );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'skt_charity_scripts' );
define('SKT_URL','https://www.sktthemes.net','skt-charity');
define('SKT_THEME_URL','https://www.sktthemes.net/themes','skt-charity');
define('SKT_THEME_DOC','https://sktthemesdemo.net/documentation/charity_documentation/','skt-charity');
define('SKT_PRO_THEME_URL','https://www.sktthemes.net/shop/charity-wordpress-theme/','skt-charity');
define('SKT_LIVE_DEMO','http://sktthemesdemo.net/charity/','skt-charity');
define('SKT_FEATURED_EMAGE','https://www.youtube.com/watch?v=310YGYtGLIM','skt-charity');
define('SKT_FREE_THEME_URL','https://www.sktthemes.net/shop/skt-charity/','skt-charity');
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/inc/custom-header.php';
/**
* Custom template for about theme.
*/
require get_template_directory() . '/inc/about-themes.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/inc/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
if ( ! function_exists( 'skt_charity_the_custom_logo' ) ) :
/**
* Displays the optional custom logo.
*
* Does nothing if the custom logo is not available.
*
*/
function skt_charity_the_custom_logo() {
if ( function_exists( 'the_custom_logo' ) ) {
the_custom_logo();
}
}
endif;
// Add a Custom CSS file to WP Admin Area
function skt_charity_admin_theme_style() {
wp_enqueue_style('custom-admin-style', get_template_directory_uri() . '/css/admin.css');
}
add_action('admin_enqueue_scripts', 'skt_charity_admin_theme_style');
</code></pre>
<p>It works perfect in pc, but in mobile there is a problem in menu so I have added the code</p>
<pre><code>add_action( 'wp_footer', 'mobile_menu_script' );
function mobile_menu_script() {
echo '<script>';
echo 'jQuery(document).ready(function($){';
echo '$('button.menu-toggle').click(function(){';
echo 'if( $('button.menu-toggle').attr('aria-expanded') == 'true' ) {';
echo '$('button.menu-toggle').attr('aria-expanded','false');';
echo '$('ul#top-menu').attr('style','display:none;');';
echo '}';
echo 'else {';
echo '$('button.menu-toggle').attr('aria-expanded','true');';
echo '$('ul#top-menu').attr('style','display:block;');';
echo '}';
echo '});';
echo '});';
echo '</script>';
}
</code></pre>
<p>and then I have updated the <code>functions.php</code> file now its blank. there is no output. please need help.</p>
|
[
{
"answer_id": 287672,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 0,
"selected": false,
"text": "<p>@inarolo has right. Your code should be looking like that:</p>\n\n<pre><code>function wpse_287665_mobile_menu_script() {\n\n echo '<script>';\n echo 'jQuery(document).ready(function($){';\n echo '$(\"button.menu-toggle\").click(function(){';\n echo 'if( $(\"button.menu-toggle\").attr(\"aria-expanded\") == \"true\" ) {';\n echo '$(\"button.menu-toggle\").attr(\"aria-expanded\", \"false\");';\n echo '$(\"ul#top-menu\").attr(\"style\", \"display:none;\");';\n echo '}';\n echo 'else {';\n echo '$(\"button.menu-toggle\").attr(\"aria-expanded\", \"true\");';\n echo '$(\"ul#top-menu\").attr(\"style\",\"display:block;\");';\n echo '}';\n echo '});';\n echo '});';\n echo '</script>';\n}\n\nadd_action( 'wp_footer', 'wpse_287665_mobile_menu_script' );\n</code></pre>\n\n<p>Also, if you have blank page try to investigate first what is the problem enablling <code>WP_DEBUG</code> constant in your <code>wp-config.php</code> file.</p>\n\n<pre><code>define( 'WP_DEBUG', true );\n</code></pre>\n\n<p>Reference:\n<a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Debugging_in_WordPress</a></p>\n"
},
{
"answer_id": 287686,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": true,
"text": "<p>The answer by @motivast is correct. However, to avoid using a billion <code>echo</code> and apostrophes, you can simply close the PHP tag and open it after your script:</p>\n\n<pre><code>function wpse_287665_mobile_menu_script() { ?>\n\n <script>\n jQuery(document).ready(function($){\n $(\"button.menu-toggle\").click(function(){\n if( $(\"button.menu-toggle\").attr(\"aria-expanded\") == \"true\" ) {\n $(\"button.menu-toggle\").attr(\"aria-expanded\", \"false\");\n $(\"ul#top-menu\").attr(\"style\", \"display:none;\");\n } else {\n $(\"button.menu-toggle\").attr(\"aria-expanded\", \"true\");\n $(\"ul#top-menu\").attr(\"style\",\"display:block;\");\n }\n });\n });\n </script><?php\n}\n\nadd_action( 'wp_footer', 'wpse_287665_mobile_menu_script' );\n</code></pre>\n\n<p>Neat, isn't it?</p>\n"
}
] |
2017/12/04
|
[
"https://wordpress.stackexchange.com/questions/287665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132645/"
] |
my initial `functions.php` is looks like this
```
<?php
/**
* SKT Charity functions and definitions
*
* @package SKT Charity
*/
global $content_width;
if ( ! isset( $content_width ) )
$content_width = 640; /* pixels */
// Set the word limit of post content
function skt_charity_content($limit) {
$content = explode(' ', get_the_content(), $limit);
if (count($content)>=$limit) {
array_pop($content);
$content = implode(" ",$content).'...';
} else {
$content = implode(" ",$content);
}
$content = preg_replace('/\[.+\]/','', $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
/**
* Set the content width based on the theme's design and stylesheet.
*/
if ( ! function_exists( 'skt_charity_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which runs
* before the init hook. The init hook is too late for some features, such as indicating
* support post thumbnails.
*/
function skt_charity_setup() {
load_theme_textdomain( 'skt-charity', get_template_directory() . '/languages' );
add_theme_support( 'automatic-feed-links' );
add_theme_support('woocommerce');
add_theme_support( 'post-thumbnails' );
add_theme_support( 'custom-header', array( 'header-text' => false ) );
add_theme_support( 'title-tag' );
add_theme_support( 'custom-logo', array(
'height' => 350,
'width' => 150,
'flex-height' => true,
) );
add_image_size('skt-charity-homepage-thumb',240,145,true);
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'skt-charity' ),
) );
add_theme_support( 'custom-background', array(
'default-color' => 'ffffff'
) );
add_editor_style( 'editor-style.css' );
}
endif; // skt_charity_setup
add_action( 'after_setup_theme', 'skt_charity_setup' );
function skt_charity_widgets_init() {
register_sidebar( array(
'name' => __( 'Blog Sidebar', 'skt-charity' ),
'description' => __( 'Appears on blog page sidebar', 'skt-charity' ),
'id' => 'sidebar-1',
'before_widget' => '',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3><aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
) );
register_sidebar( array(
'name' => __( 'Header Left Widget', 'skt-charity' ),
'description' => __( 'Appears on left site of header', 'skt-charity' ),
'id' => 'header-info-left',
'before_widget' => '<div class="headerinfo">',
'after_widget' => '</div>',
'before_title' => '<h3 style="display:none">',
'after_title' => '</h3>',
) );
register_sidebar( array(
'name' => __( 'Header Right Widget', 'skt-charity' ),
'description' => __( 'Appears on right site of header', 'skt-charity' ),
'id' => 'header-info-right',
'before_widget' => '<div class="headerinfo">',
'after_widget' => '</div>',
'before_title' => '<h3 style="display:none">',
'after_title' => '</h3>',
) );
}
add_action( 'widgets_init', 'skt_charity_widgets_init' );
function skt_charity_font_url(){
$font_url = '';
/* Translators: If there are any character that are not
* supported by Roboto, trsnalate this to off, do not
* translate into your own language.
*/
$roboto = _x('on','roboto:on or off','skt-charity');
/* Translators: If there has any character that are not supported
* by Scada, translate this to off, do not translate
* into your own language.
*/
$scada = _x('on','Scada:on or off','skt-charity');
if('off' !== $roboto ){
$font_family = array();
if('off' !== $roboto){
$font_family[] = 'Roboto:300,400,600,700,800,900';
}
$query_args = array(
'family' => urlencode(implode('|',$font_family)),
);
$font_url = add_query_arg($query_args,'//fonts.googleapis.com/css');
}
return $font_url;
}
function skt_charity_scripts() {
wp_enqueue_style('skt-charity-font', skt_charity_font_url(), array());
wp_enqueue_style( 'skt-charity-basic-style', get_stylesheet_uri() );
wp_enqueue_style( 'skt-charity-editor-style', get_template_directory_uri().'/editor-style.css' );
wp_enqueue_style( 'nivoslider-style', get_template_directory_uri().'/css/nivo-slider.css' );
wp_enqueue_style( 'skt-charity-main-style', get_template_directory_uri().'/css/responsive.css' );
wp_enqueue_style( 'skt-charity-base-style', get_template_directory_uri().'/css/style_base.css' );
wp_enqueue_script( 'skt-charity-nivo-script', get_template_directory_uri() . '/js/jquery.nivo.slider.js', array('jquery') );
wp_enqueue_script( 'skt-charity-custom_js', get_template_directory_uri() . '/js/custom.js' );
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
add_action( 'wp_enqueue_scripts', 'skt_charity_scripts' );
define('SKT_URL','https://www.sktthemes.net','skt-charity');
define('SKT_THEME_URL','https://www.sktthemes.net/themes','skt-charity');
define('SKT_THEME_DOC','https://sktthemesdemo.net/documentation/charity_documentation/','skt-charity');
define('SKT_PRO_THEME_URL','https://www.sktthemes.net/shop/charity-wordpress-theme/','skt-charity');
define('SKT_LIVE_DEMO','http://sktthemesdemo.net/charity/','skt-charity');
define('SKT_FEATURED_EMAGE','https://www.youtube.com/watch?v=310YGYtGLIM','skt-charity');
define('SKT_FREE_THEME_URL','https://www.sktthemes.net/shop/skt-charity/','skt-charity');
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/inc/custom-header.php';
/**
* Custom template for about theme.
*/
require get_template_directory() . '/inc/about-themes.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/inc/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/inc/extras.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/inc/customizer.php';
if ( ! function_exists( 'skt_charity_the_custom_logo' ) ) :
/**
* Displays the optional custom logo.
*
* Does nothing if the custom logo is not available.
*
*/
function skt_charity_the_custom_logo() {
if ( function_exists( 'the_custom_logo' ) ) {
the_custom_logo();
}
}
endif;
// Add a Custom CSS file to WP Admin Area
function skt_charity_admin_theme_style() {
wp_enqueue_style('custom-admin-style', get_template_directory_uri() . '/css/admin.css');
}
add_action('admin_enqueue_scripts', 'skt_charity_admin_theme_style');
```
It works perfect in pc, but in mobile there is a problem in menu so I have added the code
```
add_action( 'wp_footer', 'mobile_menu_script' );
function mobile_menu_script() {
echo '<script>';
echo 'jQuery(document).ready(function($){';
echo '$('button.menu-toggle').click(function(){';
echo 'if( $('button.menu-toggle').attr('aria-expanded') == 'true' ) {';
echo '$('button.menu-toggle').attr('aria-expanded','false');';
echo '$('ul#top-menu').attr('style','display:none;');';
echo '}';
echo 'else {';
echo '$('button.menu-toggle').attr('aria-expanded','true');';
echo '$('ul#top-menu').attr('style','display:block;');';
echo '}';
echo '});';
echo '});';
echo '</script>';
}
```
and then I have updated the `functions.php` file now its blank. there is no output. please need help.
|
The answer by @motivast is correct. However, to avoid using a billion `echo` and apostrophes, you can simply close the PHP tag and open it after your script:
```
function wpse_287665_mobile_menu_script() { ?>
<script>
jQuery(document).ready(function($){
$("button.menu-toggle").click(function(){
if( $("button.menu-toggle").attr("aria-expanded") == "true" ) {
$("button.menu-toggle").attr("aria-expanded", "false");
$("ul#top-menu").attr("style", "display:none;");
} else {
$("button.menu-toggle").attr("aria-expanded", "true");
$("ul#top-menu").attr("style","display:block;");
}
});
});
</script><?php
}
add_action( 'wp_footer', 'wpse_287665_mobile_menu_script' );
```
Neat, isn't it?
|
287,677 |
<p>I'm using a WordPress REST API to get contents of a page. The URL I'm using is:</p>
<blockquote>
<p><a href="https://sitename.org/wp-json/wp/v2/pages/4322" rel="nofollow noreferrer">https://sitename.org/wp-json/wp/v2/pages/4322</a></p>
</blockquote>
<p>When I open that URL in browser, I'm getting back valid response. </p>
<p>But when I try to use that same URL via cURL, I'm getting:</p>
<blockquote>
<p>couldn't connect to host</p>
</blockquote>
<p>The code I'm using is this:</p>
<pre><code>$page_id = 4322;
$wp_api_url = "https://sitename.org/wp-json/wp/v2/pages/".$page_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $wp_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
if (FALSE === $response)
{
echo curl_error($ch); // <---- failing here
}
else
{
echo '<pre>';
print_r(json_decode($response, true));
echo '</pre>';
}
curl_close($ch);
</code></pre>
<p>Which begs the question:</p>
<ol>
<li>Why does it work via a browser then?</li>
<li>Do I have to use some kind of authentication while calling an API via cURL?</li>
</ol>
|
[
{
"answer_id": 287683,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following code and should work, if not we should see the server configuration to see why. Also, we can check the curl_error for hints.</p>\n\n<pre><code>$curl = curl_init();\n$page_id = 4322;\n$wp_api_url = \"https://sitename.org/wp-json/wp/v2/pages/\".$page_id; \ncurl_setopt_array($curl, array(\n CURLOPT_URL => $wp_api_url,\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"GET\",\n));\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n</code></pre>\n"
},
{
"answer_id": 373747,
"author": "Asuka165",
"author_id": 111692,
"author_profile": "https://wordpress.stackexchange.com/users/111692",
"pm_score": 1,
"selected": false,
"text": "<p>It seem I am very late for this question, but I post my experience to here anyway, and hope it can help anyone with similar experience, since it is so hard to google an answer for this kind of rare situation.</p>\n<p>I have a very similar problem.\nI tested thru Browser and AJAX, they are OK,\nbut I got connection timed out when I send the request with PHP cURL.</p>\n<p>But my situation is a bit different.\nI have 2 servers, server A is the host of the API, and server B is the requesting server.</p>\n<p>Server B is my production server that, people have been using it without any problem, until one day, I got connection timed out error from Server A.</p>\n<p>Then, I found out that, Server A firewall blacklisted Server B, because Server B tried to perform SQL injection. (That is why browser and AJAX didn't blocked by Server A, because you are sending the request from your PC, not thru the server)\n<strong>So, I solved my problem by whitelisting Server B in Server A.</strong></p>\n<p>But the story is not end yet.\nThe reason why server A blacklist server B was because one of my user enter a big chunk of paragraph via the API that contain the word "<code>select</code>ed" (it is <strong>selected</strong>, not <code>select</code> alone) and "<strong>from</strong>", for some reason the server A marked it as SQL injection.\nIt sound weird, but I guess the server's ModSecurity is too sensitive.</p>\n"
}
] |
2017/12/04
|
[
"https://wordpress.stackexchange.com/questions/287677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132653/"
] |
I'm using a WordPress REST API to get contents of a page. The URL I'm using is:
>
> <https://sitename.org/wp-json/wp/v2/pages/4322>
>
>
>
When I open that URL in browser, I'm getting back valid response.
But when I try to use that same URL via cURL, I'm getting:
>
> couldn't connect to host
>
>
>
The code I'm using is this:
```
$page_id = 4322;
$wp_api_url = "https://sitename.org/wp-json/wp/v2/pages/".$page_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $wp_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
if (FALSE === $response)
{
echo curl_error($ch); // <---- failing here
}
else
{
echo '<pre>';
print_r(json_decode($response, true));
echo '</pre>';
}
curl_close($ch);
```
Which begs the question:
1. Why does it work via a browser then?
2. Do I have to use some kind of authentication while calling an API via cURL?
|
It seem I am very late for this question, but I post my experience to here anyway, and hope it can help anyone with similar experience, since it is so hard to google an answer for this kind of rare situation.
I have a very similar problem.
I tested thru Browser and AJAX, they are OK,
but I got connection timed out when I send the request with PHP cURL.
But my situation is a bit different.
I have 2 servers, server A is the host of the API, and server B is the requesting server.
Server B is my production server that, people have been using it without any problem, until one day, I got connection timed out error from Server A.
Then, I found out that, Server A firewall blacklisted Server B, because Server B tried to perform SQL injection. (That is why browser and AJAX didn't blocked by Server A, because you are sending the request from your PC, not thru the server)
**So, I solved my problem by whitelisting Server B in Server A.**
But the story is not end yet.
The reason why server A blacklist server B was because one of my user enter a big chunk of paragraph via the API that contain the word "`select`ed" (it is **selected**, not `select` alone) and "**from**", for some reason the server A marked it as SQL injection.
It sound weird, but I guess the server's ModSecurity is too sensitive.
|
287,678 |
<p>Is there a way to count the amount of posts in a CPT and add a different class to 1/3 of said posts? </p>
<p>I am using Masonry for a grid and want two different image sizes displayed randomly. I got all that working but the images aren't aligning perfectly which is why the grid looks off (with gaps in between). I figured if 1/3 of the posts are smaller size it would align better. </p>
<p>So what I want is:</p>
<ul>
<li>Grid with two different image sizes that changes on refresh (so the layout is different with each refresh and the large & small images switch)</li>
<li>The loop displays the items randomly </li>
</ul>
<p>This is my current code: </p>
<pre><code> <?php
/**
* Template Name: Teampagina
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Deliciae Design custom
* @since 1.0.0
*/
get_header(); ?>
<div id="primary" <?php astra_primary_class(); ?>>
<?php astra_primary_content_top(); ?>
<main id="main" class="site-main team-page" role="main">
<header class="entry-header <?php astra_entry_header_class(); ?>">
<h1 class="entry-title text-center" itemprop="headline"><?php echo post_type_archive_title(); ?></h1>
<form class="quicksearch">
<div class="input-group">
<input type="text" id="qs-input" placeholder="Zoek op naam">
<i class="fa fa-search"></i>
</div>
</form><!-- quicksearch -->
</header><!-- .entry-header -->
<?php
$args = array(
'orderby' => 'rand',
'post_type' => 'focus_team'
);
$query = new WP_Query( $args );
$count = 0; if ( $query->have_posts() ) : ?>
<ul id="team-masonry">
<li class="grid-sizer"></li>
<?php while ( $query->have_posts() ) : $query->the_post();
?>
<li class="grid-item size-<?php echo rand(1,2); ?>">
<a href="<?php echo get_post_permalink(); ?>">
<div class="fo--info">
<?php the_post_thumbnail('team_member'); ?>
<div class="fo--overlay">
<div class="table">
<div class="item">
<?php the_title( '<h3 class="entry-title" itemprop="headline">', '</h3>' ); ?>
<p>functie</p>
</div>
</div>
</div>
</div>
</a>
</li>
<?php endwhile; wp_reset_postdata(); ?><!-- reset loop -->
</ul>
<?php endif;?>
</main><!-- #main -->
<?php astra_primary_content_bottom(); ?>
</div><!-- #primary -->
<?php get_footer(); ?>
<script>
(function($){
var qsRegex;
var $container = $('#team-masonry');
$container.isotope({
itemSelector: '.grid-item'
});
var $grid = $('#team-masonry').isotope({
resizable: true,
// set itemSelector so .grid-sizer is not used in layout
itemSelector: '.grid-item',
columnWidth: 300,
masonry: {
columnWidth: '.grid-sizer'
},
filter: function() {
return qsRegex ? $(this).text().match( qsRegex ) : true;
}
});
// layout Isotope after each image loads
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
// use value of search field to filter
var $quicksearch = $('input#qs-input').keyup( debounce( function() {
qsRegex = new RegExp( $quicksearch.val(), 'gi' );
$grid.isotope();
}, 200 ) );
// debounce so filtering doesn't happen every millisecond
function debounce( fn, threshold ) {
var timeout;
return function debounced() {
if ( timeout ) {
clearTimeout( timeout );
}
function delayed() {
fn();
timeout = null;
}
timeout = setTimeout( delayed, threshold || 100 );
}
}
})( jQuery );
</script>
</code></pre>
|
[
{
"answer_id": 287683,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following code and should work, if not we should see the server configuration to see why. Also, we can check the curl_error for hints.</p>\n\n<pre><code>$curl = curl_init();\n$page_id = 4322;\n$wp_api_url = \"https://sitename.org/wp-json/wp/v2/pages/\".$page_id; \ncurl_setopt_array($curl, array(\n CURLOPT_URL => $wp_api_url,\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"GET\",\n));\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n</code></pre>\n"
},
{
"answer_id": 373747,
"author": "Asuka165",
"author_id": 111692,
"author_profile": "https://wordpress.stackexchange.com/users/111692",
"pm_score": 1,
"selected": false,
"text": "<p>It seem I am very late for this question, but I post my experience to here anyway, and hope it can help anyone with similar experience, since it is so hard to google an answer for this kind of rare situation.</p>\n<p>I have a very similar problem.\nI tested thru Browser and AJAX, they are OK,\nbut I got connection timed out when I send the request with PHP cURL.</p>\n<p>But my situation is a bit different.\nI have 2 servers, server A is the host of the API, and server B is the requesting server.</p>\n<p>Server B is my production server that, people have been using it without any problem, until one day, I got connection timed out error from Server A.</p>\n<p>Then, I found out that, Server A firewall blacklisted Server B, because Server B tried to perform SQL injection. (That is why browser and AJAX didn't blocked by Server A, because you are sending the request from your PC, not thru the server)\n<strong>So, I solved my problem by whitelisting Server B in Server A.</strong></p>\n<p>But the story is not end yet.\nThe reason why server A blacklist server B was because one of my user enter a big chunk of paragraph via the API that contain the word "<code>select</code>ed" (it is <strong>selected</strong>, not <code>select</code> alone) and "<strong>from</strong>", for some reason the server A marked it as SQL injection.\nIt sound weird, but I guess the server's ModSecurity is too sensitive.</p>\n"
}
] |
2017/12/04
|
[
"https://wordpress.stackexchange.com/questions/287678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132652/"
] |
Is there a way to count the amount of posts in a CPT and add a different class to 1/3 of said posts?
I am using Masonry for a grid and want two different image sizes displayed randomly. I got all that working but the images aren't aligning perfectly which is why the grid looks off (with gaps in between). I figured if 1/3 of the posts are smaller size it would align better.
So what I want is:
* Grid with two different image sizes that changes on refresh (so the layout is different with each refresh and the large & small images switch)
* The loop displays the items randomly
This is my current code:
```
<?php
/**
* Template Name: Teampagina
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Deliciae Design custom
* @since 1.0.0
*/
get_header(); ?>
<div id="primary" <?php astra_primary_class(); ?>>
<?php astra_primary_content_top(); ?>
<main id="main" class="site-main team-page" role="main">
<header class="entry-header <?php astra_entry_header_class(); ?>">
<h1 class="entry-title text-center" itemprop="headline"><?php echo post_type_archive_title(); ?></h1>
<form class="quicksearch">
<div class="input-group">
<input type="text" id="qs-input" placeholder="Zoek op naam">
<i class="fa fa-search"></i>
</div>
</form><!-- quicksearch -->
</header><!-- .entry-header -->
<?php
$args = array(
'orderby' => 'rand',
'post_type' => 'focus_team'
);
$query = new WP_Query( $args );
$count = 0; if ( $query->have_posts() ) : ?>
<ul id="team-masonry">
<li class="grid-sizer"></li>
<?php while ( $query->have_posts() ) : $query->the_post();
?>
<li class="grid-item size-<?php echo rand(1,2); ?>">
<a href="<?php echo get_post_permalink(); ?>">
<div class="fo--info">
<?php the_post_thumbnail('team_member'); ?>
<div class="fo--overlay">
<div class="table">
<div class="item">
<?php the_title( '<h3 class="entry-title" itemprop="headline">', '</h3>' ); ?>
<p>functie</p>
</div>
</div>
</div>
</div>
</a>
</li>
<?php endwhile; wp_reset_postdata(); ?><!-- reset loop -->
</ul>
<?php endif;?>
</main><!-- #main -->
<?php astra_primary_content_bottom(); ?>
</div><!-- #primary -->
<?php get_footer(); ?>
<script>
(function($){
var qsRegex;
var $container = $('#team-masonry');
$container.isotope({
itemSelector: '.grid-item'
});
var $grid = $('#team-masonry').isotope({
resizable: true,
// set itemSelector so .grid-sizer is not used in layout
itemSelector: '.grid-item',
columnWidth: 300,
masonry: {
columnWidth: '.grid-sizer'
},
filter: function() {
return qsRegex ? $(this).text().match( qsRegex ) : true;
}
});
// layout Isotope after each image loads
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
// use value of search field to filter
var $quicksearch = $('input#qs-input').keyup( debounce( function() {
qsRegex = new RegExp( $quicksearch.val(), 'gi' );
$grid.isotope();
}, 200 ) );
// debounce so filtering doesn't happen every millisecond
function debounce( fn, threshold ) {
var timeout;
return function debounced() {
if ( timeout ) {
clearTimeout( timeout );
}
function delayed() {
fn();
timeout = null;
}
timeout = setTimeout( delayed, threshold || 100 );
}
}
})( jQuery );
</script>
```
|
It seem I am very late for this question, but I post my experience to here anyway, and hope it can help anyone with similar experience, since it is so hard to google an answer for this kind of rare situation.
I have a very similar problem.
I tested thru Browser and AJAX, they are OK,
but I got connection timed out when I send the request with PHP cURL.
But my situation is a bit different.
I have 2 servers, server A is the host of the API, and server B is the requesting server.
Server B is my production server that, people have been using it without any problem, until one day, I got connection timed out error from Server A.
Then, I found out that, Server A firewall blacklisted Server B, because Server B tried to perform SQL injection. (That is why browser and AJAX didn't blocked by Server A, because you are sending the request from your PC, not thru the server)
**So, I solved my problem by whitelisting Server B in Server A.**
But the story is not end yet.
The reason why server A blacklist server B was because one of my user enter a big chunk of paragraph via the API that contain the word "`select`ed" (it is **selected**, not `select` alone) and "**from**", for some reason the server A marked it as SQL injection.
It sound weird, but I guess the server's ModSecurity is too sensitive.
|
287,763 |
<p>I am using <code>wp_mail()</code> function to send email to user in WordPress. I want to hide sender name like I want to mask sender email as <code>[email protected]</code> etc.</p>
<p>Any help will be appreciated.</p>
|
[
{
"answer_id": 287764,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": true,
"text": "<p>See <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/#using-headers-to-set-from-cc-and-bcc-parameters\" rel=\"nofollow noreferrer\">the documentation</a>:</p>\n\n<blockquote>\n <p>To set the “From:” email address to something other than the WordPress\n default sender, or to add “Cc:” and/or “Bcc:” recipients, you must use\n the $headers argument.</p>\n \n <p>$headers can be a string or an array, but it may be easiest to use in\n the array form. To use it, push a string onto the array, starting with\n “From:”, “Bcc:” or “Cc:” (note the use of the “:”), followed by a\n valid email address.</p>\n</blockquote>\n\n<p>This example from the <a href=\"https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes\" rel=\"nofollow noreferrer\">User Contributed Notes</a> shows you how to use it:</p>\n\n<pre><code><?php\n// assumes $to, $subject, $message have already been defined earlier...\n\n$headers[] = 'From: Me Myself <[email protected]>';\n$headers[] = 'Cc: John Q Codex <[email protected]>';\n$headers[] = 'Cc: [email protected]'; // note you can just use a simple email address\n\nwp_mail( $to, $subject, $message, $headers );\n?>\n</code></pre>\n\n<p>As you can see, you can set the From name and address by adding <code>'From: Me Myself <[email protected]>'</code> to the <code>$headers</code> argument of <code>wp_mail()</code>.</p>\n"
},
{
"answer_id": 287766,
"author": "inarilo",
"author_id": 17923,
"author_profile": "https://wordpress.stackexchange.com/users/17923",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Using the two ‘wp_mail_from’ and ‘wp_mail_from_name’ hooks allow from\n creating a from address like ‘Name [email protected]‘ when both are\n set. If just ‘wp_mail_from’ is set, then just the email address will\n be used with no name.</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_from\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_from</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_from_name\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_from_name</a></p>\n\n<p>As the other answer mentions, you can use the headers argument to specify the From name and address, but if you look at the source code comments you'll see it is supported now only for legacy reasons.</p>\n"
}
] |
2017/12/05
|
[
"https://wordpress.stackexchange.com/questions/287763",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132725/"
] |
I am using `wp_mail()` function to send email to user in WordPress. I want to hide sender name like I want to mask sender email as `[email protected]` etc.
Any help will be appreciated.
|
See [the documentation](https://developer.wordpress.org/reference/functions/wp_mail/#using-headers-to-set-from-cc-and-bcc-parameters):
>
> To set the “From:” email address to something other than the WordPress
> default sender, or to add “Cc:” and/or “Bcc:” recipients, you must use
> the $headers argument.
>
>
> $headers can be a string or an array, but it may be easiest to use in
> the array form. To use it, push a string onto the array, starting with
> “From:”, “Bcc:” or “Cc:” (note the use of the “:”), followed by a
> valid email address.
>
>
>
This example from the [User Contributed Notes](https://developer.wordpress.org/reference/functions/wp_mail/#user-contributed-notes) shows you how to use it:
```
<?php
// assumes $to, $subject, $message have already been defined earlier...
$headers[] = 'From: Me Myself <[email protected]>';
$headers[] = 'Cc: John Q Codex <[email protected]>';
$headers[] = 'Cc: [email protected]'; // note you can just use a simple email address
wp_mail( $to, $subject, $message, $headers );
?>
```
As you can see, you can set the From name and address by adding `'From: Me Myself <[email protected]>'` to the `$headers` argument of `wp_mail()`.
|
287,830 |
<pre><code>Warning: The type attribute is unnecessary for JavaScript resources.
From line 10, column 146; to line 10, column 176
feed/" /> <script type="text/javascript">window
Warning: The type attribute for the style element is not needed and should be omitted.
From line 11, column 1798; to line 11, column 1820
</script> <style type="text/css">img.wp
Warning: The type attribute for the style element is not needed and should be omitted.
From line 23, column 193; to line 23, column 251
a='all' /><style id='kirki-styles-global-inline-css' type='text/css'>.envel
Warning: The type attribute is unnecessary for JavaScript resources.
From line 23, column 905; to line 23, column 1010
}</style> <script async type="text/javascript" src="http://....../wp-content/cache/minify/df983.js"></scri
Warning: The type attribute for the style element is not needed and should be omitted.
From line 70, column 126; to line 70, column 167
70.png" /><style type="text/css" id="wp-custom-css">@media
Warning: The type attribute is unnecessary for JavaScript resources.
From line 441, column 156; to line 441, column 261
iv></div> <script defer type="text/javascript" src="http://......./wp-content/cache/minify/26938.js"></scri
Warning: The type attribute is unnecessary for JavaScript resources.
From line 441, column 272; to line 441, column 302
</script> <script type='text/javascript'>/* */
Warning: The type attribute is unnecessary for JavaScript resources.
From line 443, column 17; to line 443, column 122
</script> <script defer type="text/javascript" src="http://......../wp-content/cache/minify/6ce07.js"></scri
</code></pre>
<p>These errors are some new introduction by W3C and they have started to creep in last 3-4 days only.<a href="https://i.stack.imgur.com/KpYXc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KpYXc.png" alt="enter image description here" /></a></p>
<p>We enqueue scripts like this →</p>
<pre><code>wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
wp_enqueue_script( 'custom-js' );
</code></pre>
<p>Can we fix this from the above enqueuing method somehow?</p>
<h1>Update →</h1>
<p>these are the actual errors. In the red box are coming from W3 total cache.<a href="https://i.stack.imgur.com/qlnGZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qlnGZ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 287833,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 4,
"selected": false,
"text": "<p>You can remove the <code>type='*'</code> attributes and values from <code>wp_enqueue</code>'ed scripts and styles, using respective <code>*_loader_tag</code> hooks.</p>\n\n<p>The following worked for me:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'myplugin_enqueue' );\n\nfunction myplugin_enqueue() {\n // wp_register_script(...\n // wp_enqueue_script(...\n}\n\n\nadd_filter('style_loader_tag', 'myplugin_remove_type_attr', 10, 2);\nadd_filter('script_loader_tag', 'myplugin_remove_type_attr', 10, 2);\n\nfunction myplugin_remove_type_attr($tag, $handle) {\n return preg_replace( \"/type=['\\\"]text\\/(javascript|css)['\\\"]/\", '', $tag );\n}\n</code></pre>\n"
},
{
"answer_id": 289109,
"author": "kiwiot",
"author_id": 71357,
"author_profile": "https://wordpress.stackexchange.com/users/71357",
"pm_score": 2,
"selected": false,
"text": "<p>Got this from the soil / roots plugin. did the job for the most part.</p>\n\n<pre><code> add_filter( 'style_loader_tag', 'clean_style_tag' );\nadd_filter( 'script_loader_tag', 'clean_script_tag' );\n\n/**\n * Clean up output of stylesheet <link> tags\n */\nfunction clean_style_tag( $input ) {\n preg_match_all( \"!<link rel='stylesheet'\\s?(id='[^']+')?\\s+href='(.*)' type='text/css' media='(.*)' />!\", $input, $matches );\n if ( empty( $matches[2] ) ) {\n return $input;\n }\n // Only display media if it is meaningful\n $media = $matches[3][0] !== '' && $matches[3][0] !== 'all' ? ' media=\"' . $matches[3][0] . '\"' : '';\n\n return '<link rel=\"stylesheet\" href=\"' . $matches[2][0] . '\"' . $media . '>' . \"\\n\";\n}\n\n/**\n * Clean up output of <script> tags\n */\nfunction clean_script_tag( $input ) {\n $input = str_replace( \"type='text/javascript' \", '', $input );\n\n return str_replace( \"'\", '\"', $input );\n}\n</code></pre>\n"
},
{
"answer_id": 292663,
"author": "nikeshulak",
"author_id": 135919,
"author_profile": "https://wordpress.stackexchange.com/users/135919",
"pm_score": 1,
"selected": false,
"text": "<p>This helped me a lot:</p>\n\n<pre><code>add_filter('script_loader_tag', 'clean_script_tag');\n function clean_script_tag($input) {\n $input = str_replace(\"type='text/javascript' \", '', $input);\n return str_replace(\"'\", '\"', $input);\n}\n</code></pre>\n\n<p>Thanks to css-tricks (LeoNovais): <a href=\"https://css-tricks.com/forums/topic/clean-up-script-tags-in-wordpress/#post-246425\" rel=\"nofollow noreferrer\">https://css-tricks.com/forums/topic/clean-up-script-tags-in-wordpress/#post-246425</a></p>\n"
},
{
"answer_id": 298192,
"author": "Daniar Ayzetulov",
"author_id": 139913,
"author_profile": "https://wordpress.stackexchange.com/users/139913",
"pm_score": -1,
"selected": false,
"text": "<p>If you are experiencing this with WP Fastest Cache you can delete type attribute manually in the plugin PHP script, this should work with other plugins too, but I don't know files where they are adding the type attribute.\nFor WP Fastest Cache you should go to wp-content/plugins/wp-fastest-cache/inc folder and open js-utilities.php then search for text/javascript and delete it with the attribute. \nI had that warning on W3 Validator and fixed it that way, also be aware that when you will update plugin that change could be reverted, to disable plugin update you can edit wpFastestCache and change plugin version to something like this 10.0.8.7.7</p>\n"
},
{
"answer_id": 303217,
"author": "realmag777",
"author_id": 21151,
"author_profile": "https://wordpress.stackexchange.com/users/21151",
"pm_score": -1,
"selected": false,
"text": "<p>You can optimize HTML code of your site as you want in 2 steps:</p>\n\n<ul>\n<li>Install this plugin: <a href=\"https://wordpress.org/plugins/autoptimize/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/autoptimize/</a></li>\n<li>Enable in the plugin options 'Optimize HTML Code?'</li>\n<li><p>In functions.php of your current wordpress theme apply next code:</p>\n\n<p>add_filter('autoptimize_html_after_minify', function($content) { </p>\n\n<pre><code> $site_url = 'https://bulk-editor.com'; \n $content = str_replace(\"type='text/javascript'\", ' ', $content);\n $content = str_replace('type=\"text/javascript\"', ' ', $content);\n\n $content = str_replace(\"type='text/css'\", ' ', $content);\n $content = str_replace('type=\"text/css\"', ' ', $content);\n\n $content = str_replace($site_url . '/wp-includes/js', '/wp-includes/js', $content);\n $content = str_replace($site_url . '/wp-content/cache/autoptimize', '/wp-content/cache/autoptimize', $content);\n $content = str_replace($site_url . '/wp-content/themes/', '/wp-content/themes/', $content);\n $content = str_replace($site_url . '/wp-content/uploads/', '/wp-content/uploads/', $content);\n $content = str_replace($site_url . '/wp-content/plugins/', '/wp-content/plugins/', $content); \n return $content; }, 10, 1);\n</code></pre>\n\n<p>and do not forget to change $site_url to your site link <strong>without</strong> slash on the end</p></li>\n</ul>\n"
},
{
"answer_id": 304306,
"author": "firxworx",
"author_id": 134244,
"author_profile": "https://wordpress.stackexchange.com/users/134244",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>style_loader_tag</code> and <code>script_loader_tag</code> approaches above look like they should work for whatever markup Wordpress is generating, in cases where the theme/plugin is using the proper enqueue functions.</p>\n\n<p>If you have offending plugins that don't cooperate (IIRC Jetpack is/was an offender unless a newer version since my recollection has revised this!), and you are <em>adamant</em> about solving this issue despite the fact that your visitors are not likely to be impacted in any way (their browser will render the page fine!), you can always go all-out and use output buffering:</p>\n\n<pre><code>add_action('wp_loaded', 'output_buffer_start');\nfunction output_buffer_start() { \n ob_start(\"output_callback\"); \n}\n\nadd_action('shutdown', 'output_buffer_end');\nfunction output_buffer_end() { \n ob_end_flush(); \n}\n\nfunction output_callback($buffer) {\n return preg_replace( \"%[ ]type=[\\'\\\"]text\\/(javascript|css)[\\'\\\"]%\", '', $buffer );\n}\n</code></pre>\n\n<p>Be warned that while this is a solution, it isn't very efficient. You'd be running <code>preg_replace()</code> on the entire \"final\" output from Wordpress before it gets sent to the client's browser, for every request. </p>\n\n<p>Output buffering is turned on at the start (<code>wp_loaded</code> hook), i.e. right as wp + theme + plugins + etc are fully loaded, and is turned off at the last moment (<code>shutdown</code> hook) which fires just before PHP shuts down execution. The regex must work through <em>everything</em>, and that could be a lot of content!</p>\n\n<p>The <code>style_loader_tag</code> and <code>script_loader_tag</code> approaches above only run the regex on a very small string (the tag itself) so the performance impact is negligible. </p>\n\n<p>I suppose if you had relatively static content and used a caching layer you could try to mitigate the performance concern.</p>\n\n<p>php manual references:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/function.ob-start.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.ob-start.php</a></li>\n<li><a href=\"http://php.net/manual/en/function.ob-end-flush.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.ob-end-flush.php</a></li>\n</ul>\n"
},
{
"answer_id": 318538,
"author": "amlcreative",
"author_id": 153589,
"author_profile": "https://wordpress.stackexchange.com/users/153589",
"pm_score": 0,
"selected": false,
"text": "<p>Building off of @realmag77. This will leverage the Autoptimize plugin to be able to filter out ALL type attributes but not break if it's not installed and activated. The fallback works fine but those scripts and stylesheets loaded through plugins won't be filtered. I don't know how else to filter them but through using the Autoptimize portion.</p>\n\n<pre><code>/* ==========================================\n Remove type attribute on JS/CSS\n (requires Autoptimize plugin and Optimize HTML checked)\n but with fallback just in case\n========================================== */\n\n// If Autoptimize is installed and activated, remove type attributes for all JS/CSS\nif ( is_plugin_active( 'autoptimize/autoptimize.php' ) ) {\n\n add_filter('autoptimize_html_after_minify', function($content) {\n\n $site_url = home_url();\n $content = str_replace(\"type='text/javascript'\", '', $content);\n $content = str_replace('type=\"text/javascript\"', '', $content);\n\n $content = str_replace(\"type='text/css'\", '', $content);\n $content = str_replace('type=\"text/css\"', '', $content);\n\n $content = str_replace($site_url . '/wp-includes/js', '/wp-includes/js', $content);\n $content = str_replace($site_url . '/wp-content/cache/autoptimize', '/wp-content/cache/autoptimize', $content);\n $content = str_replace($site_url . '/wp-content/themes/', '/wp-content/themes/', $content);\n $content = str_replace($site_url . '/wp-content/uploads/', '/wp-content/uploads/', $content);\n $content = str_replace($site_url . '/wp-content/plugins/', '/wp-content/plugins/', $content);\n\n return $content;\n\n }, 10, 1);\n\n} else {\n\n // Fallback to remove type attributes except for those loaded through plugins\n add_filter('style_loader_tag', 'pss_remove_type_attr', 10, 2);\n add_filter('script_loader_tag', 'pss_remove_type_attr', 10, 2);\n function pss_remove_type_attr($tag, $handle) {\n return preg_replace( \"/type=['\\\"]text\\/(javascript|css)['\\\"]/\", '', $tag );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 336770,
"author": "Jeevan Singla",
"author_id": 167152,
"author_profile": "https://wordpress.stackexchange.com/users/167152",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action('wp_loaded', 'prefix_output_buffer_start');\nfunction prefix_output_buffer_start() { \n ob_start(\"prefix_output_callback\"); \n}\n\nadd_action('shutdown', 'prefix_output_buffer_end');\nfunction prefix_output_buffer_end() { \n ob_end_flush(); \n}\n\nfunction prefix_output_callback($buffer) {\n return preg_replace( \"%[ ]type=[\\'\\\"]text\\/(javascript|css)[\\'\\\"]%\", '', $buffer );\n}\n</code></pre>\n"
},
{
"answer_id": 353536,
"author": "Infoconic Technologies",
"author_id": 179066,
"author_profile": "https://wordpress.stackexchange.com/users/179066",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the functions below to remove type attributes from link and script tags.</p>\n\n<p>Paste the function below in functions.php for removing the type=text/css from <code>link</code> tags</p>\n\n<pre>/* Remove the attribute \" 'type=text/css' \" from stylesheet */\nfunction wpse51581_hide_type($src) {\n return str_replace(\"type='text/css'\", '', $src);\n}\nadd_filter('style_loader_tag', 'wpse51581_hide_type');</pre>\n\n<p>===========================================================================</p>\n\n<p>Paste the function below in functions.php for removing the type='text/javascript' from <code>script</code></p>\n\n<pre>//* Remove type tag from script and style\nadd_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);\nfunction codeless_remove_type_attr($tag, $handle) {\n return preg_replace( \"/type=['\\\"]text\\/(javascript|css)['\\\"]/\", '', $tag );\n}</pre>\n"
},
{
"answer_id": 353546,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 5,
"selected": false,
"text": "<p>WordPress 5.3 introduces a considerably simpler way to achieve this. By registering theme support for HTML 5 for <code>script</code> and <code>style</code>, the <code>type=\"\"</code> attribute will be omitted:</p>\n\n<pre><code>add_action(\n 'after_setup_theme',\n function() {\n add_theme_support( 'html5', [ 'script', 'style' ] );\n }\n);\n</code></pre>\n"
},
{
"answer_id": 354013,
"author": "Jodyshop",
"author_id": 127580,
"author_profile": "https://wordpress.stackexchange.com/users/127580",
"pm_score": 0,
"selected": false,
"text": "<p>Well, because I've tried tons of other codes and the ones mentioned here, There are still traces of the <code>text/javascript</code> from WordPress core files and also from other plugin and inline javascript codes. After testing this code, everything has been resolved:</p>\n\n<pre><code>// Remove w3 validator regarding \"text/javascript\"\nadd_action('wp_loaded', 'prefix_output_buffer_start');\nfunction prefix_output_buffer_start() { \n ob_start(\"prefix_output_callback\"); \n}\nadd_action('shutdown', 'prefix_output_buffer_end');\nfunction prefix_output_buffer_end() { \n ob_end_flush(); \n}\nfunction prefix_output_callback($buffer) {\n return preg_replace( \"%[ ]type=[\\'\\\"]text\\/(javascript|css)[\\'\\\"]%\", '', $buffer );\n}\n</code></pre>\n\n<p>Hope it can help some :)</p>\n\n<p>Thank you</p>\n"
},
{
"answer_id": 354684,
"author": "cyberwani",
"author_id": 28568,
"author_profile": "https://wordpress.stackexchange.com/users/28568",
"pm_score": 1,
"selected": false,
"text": "<p>According to code in script-loader.php <strong>type</strong> attribute is omitted when html5 theme support is added with script and style arguments.</p>\n\n<p>See below links:</p>\n\n<ul>\n<li><a href=\"https://build.trac.wordpress.org/browser/tags/5.3/wp-includes/script-loader.php#L2576\" rel=\"nofollow noreferrer\">https://build.trac.wordpress.org/browser/tags/5.3/wp-includes/script-loader.php#L2576</a></li>\n<li><a href=\"https://build.trac.wordpress.org/browser/tags/5.3/wp-includes/script-loader.php#L2758\" rel=\"nofollow noreferrer\">https://build.trac.wordpress.org/browser/tags/5.3/wp-includes/script-loader.php#L2758</a></li>\n</ul>\n\n<pre class=\"lang-php prettyprint-override\"><code>function yourthemeprefix_theme_supportt() {\n add_theme_support(\n 'html5',\n array(\n 'script', // Fix for: The \"type\" attribute is unnecessary for JavaScript resources.\n 'style', // Fix for: The \"type\" attribute for the \"style\" element is not needed and should be omitted.\n )\n );\n}\nadd_action( 'after_setup_theme', 'yourthemeprefix_theme_support' );\n</code></pre>\n"
}
] |
2017/12/05
|
[
"https://wordpress.stackexchange.com/questions/287830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] |
```
Warning: The type attribute is unnecessary for JavaScript resources.
From line 10, column 146; to line 10, column 176
feed/" /> <script type="text/javascript">window
Warning: The type attribute for the style element is not needed and should be omitted.
From line 11, column 1798; to line 11, column 1820
</script> <style type="text/css">img.wp
Warning: The type attribute for the style element is not needed and should be omitted.
From line 23, column 193; to line 23, column 251
a='all' /><style id='kirki-styles-global-inline-css' type='text/css'>.envel
Warning: The type attribute is unnecessary for JavaScript resources.
From line 23, column 905; to line 23, column 1010
}</style> <script async type="text/javascript" src="http://....../wp-content/cache/minify/df983.js"></scri
Warning: The type attribute for the style element is not needed and should be omitted.
From line 70, column 126; to line 70, column 167
70.png" /><style type="text/css" id="wp-custom-css">@media
Warning: The type attribute is unnecessary for JavaScript resources.
From line 441, column 156; to line 441, column 261
iv></div> <script defer type="text/javascript" src="http://......./wp-content/cache/minify/26938.js"></scri
Warning: The type attribute is unnecessary for JavaScript resources.
From line 441, column 272; to line 441, column 302
</script> <script type='text/javascript'>/* */
Warning: The type attribute is unnecessary for JavaScript resources.
From line 443, column 17; to line 443, column 122
</script> <script defer type="text/javascript" src="http://......../wp-content/cache/minify/6ce07.js"></scri
```
These errors are some new introduction by W3C and they have started to creep in last 3-4 days only.[](https://i.stack.imgur.com/KpYXc.png)
We enqueue scripts like this →
```
wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
wp_enqueue_script( 'custom-js' );
```
Can we fix this from the above enqueuing method somehow?
Update →
========
these are the actual errors. In the red box are coming from W3 total cache.[](https://i.stack.imgur.com/qlnGZ.png)
|
WordPress 5.3 introduces a considerably simpler way to achieve this. By registering theme support for HTML 5 for `script` and `style`, the `type=""` attribute will be omitted:
```
add_action(
'after_setup_theme',
function() {
add_theme_support( 'html5', [ 'script', 'style' ] );
}
);
```
|
287,857 |
<p>I am not asking you to write the all code or asking a plugin, I am asking a way to build this feature because I don't have any plan in my mind to build this feature.</p>
<p>This is the requirement : There are many posts on the website. Logged Users (Front-end users) should have a feature to save list of posts.</p>
<p>Ex : </p>
<ul>
<li>List 01 : My favorite Posts</li>
<li>List 02 : Blogging related posts</li>
<li>List 03 : Watch later Posts</li>
</ul>
<p>I want user to allow to create these types of list. Then they can add any number of posts. And these list are private. I mean only created user can access the list.</p>
<p><strong>This is something like we label emails on gmail.</strong></p>
<p>What can I use to save list? I have no idea what can I use for it... At least is this possible with WordPress?</p>
|
[
{
"answer_id": 287877,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest using using custom tables to keep things lean.</p>\n\n<p>Have two tables: A table of lists and a table of posts and which lists they belong to. </p>\n\n<p>The lists table (let's call it <code>wp_lists</code>) would look like:</p>\n\n<pre><code>+----+---------+----------------+\n| id | user_id | name |\n+----+---------+----------------+\n| 1 | 2 | My list |\n| 2 | 2 | My second list |\n+----+---------+----------------+\n</code></pre>\n\n<p>You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.</p>\n\n<p>And the lists-posts table (let's call it <code>wp_post_list</code>) would look like:</p>\n\n<pre><code>+---------+---------+\n| post_id | list_id |\n+---------+---------+\n| 2 | 2 |\n| 3 | 2 |\n| 2 | 1 |\n+---------+---------+\n</code></pre>\n\n<p>Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the <code>post_id</code>/<code>list_id</code> combinations should all be unique, since posts can't be in a list more than once. </p>\n\n<p>So when someone creates a list you'd insert it into <code>wp_lists</code>. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.</p>\n\n<p>To get the lists that belong to the current user you'd just query <code>wp_lists</code> based on the <code>user_id</code> column.</p>\n\n<p>When someone adds a post to a list you'd insert the post ID into <code>wp_post_list</code> alongside the list it belongs to. When you want to see all posts within a list you'd query based on the <code>list_id</code> column, then put the resulting IDs into a <code>WP_Query</code> or <code>get_posts()</code>.</p>\n\n<p>When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query <code>wp_post_list</code> based on the <code>post_id</code>, but <code>JOIN</code> it to <code>wp_lists</code> and limit results to ones with lists that have the current user's ID.</p>\n"
},
{
"answer_id": 287879,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a button on the front and save the ID of the currently displayed post in user's meta. Here's a simple way to do this:</p>\n\n<h2>Output a Button on Front</h2>\n\n<p>You need to create a button in your <code>single.php</code> ( or whatever page you want ) to allow the user to actually set the post as a favorite. The below template does this. The <code>like-overlay</code> class is used to create a loading effect while the request is being processed.</p>\n\n<pre><code><div id=\"like-button\" class=\"like btn btn-default\" type=\"button\">\n <span class=\"fa fa-heart\"></span>\n <span class=\"like-overlay\"><i class=\"fa fa-spin fa-circle-o-notch\"></i></span>\n</div>\n<input type=\"hidden\" value=\"<?php the_ID(); ?>\" id=\"current-post-id\"/>\n<input type=\"hidden\" value=\"<?php echo get_current_user_id(); ?>\" id=\"current-user-id\"/>\n</code></pre>\n\n<h2>Add a Click event to the Button</h2>\n\n<p>When the user clicks the button, send an AJAX request to the server, and update the button based on the results. You might need to localize the script to pass the rest URL and other data.</p>\n\n<pre><code>$('#like-button').on('click',function (e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: 'http://example.com/wp-json/my_route/v1/ajax_favorite',\n data: { post_id: $('#current-post-id').val(), user_id : $('#current-user-id').val() },\n beforeSend: function() {\n $('#like-button').addClass('active').prop('disabled', true);\n },\n success: function(data){\n\n $('#like-button').removeClass('active').prop('disabled', false);\n\n if( data != null ){\n\n if( data == '400' ) {\n $('#like-button').removeClass('selected');\n } else if( data == '200') {\n $('#like-button').addClass('selected');\n }\n }\n },\n error:function(){\n\n }\n });\n});\n</code></pre>\n\n<h2>Process the Ajax Request Using REST-API</h2>\n\n<p>Now create a rest route and process the data. If the received post ID doesn't exists in the user meta, add it and return a successful code. If it does, remove it and let your script know about it.</p>\n\n<pre><code>add_action( 'rest_api_init', 'my_rest_routes');\nfunction my_rest_routes() {\n // Path to ajax like function\n register_rest_route(\n 'my_route/v1',\n '/ajax_favorite/',\n array(\n 'methods' => 'GET',\n 'callback' => 'ajax_favorite'\n )\n );\n}\n\nfunction ajax_favorite(){\n\n // If the ID is not set, return\n if(!isset($_GET['post_id']) || !isset($_GET['user_id'])){\n return $data['status'] = '500';\n }\n\n // Store user and product's ID\n $post_id = sanitize_text_field($_GET['post_id']);\n $user_id = sanitize_text_field($_GET['user_id']);\n $user_meta = get_user_meta($user_id,'_favorite_posts',false);\n\n // Check if the post is favorited or not\n if( in_array( $post_id, $user_meta ) ){\n delete_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '400';\n } else {\n add_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '200';\n }\n\n}\n</code></pre>\n\n<p>You can use this as a template to output any button that saves data from front-end to database. Don't forget to sanitize the data, and use nonce too.</p>\n\n<p>Now of course all you need is to get the <code>_favorite_posts</code> user meta whenever you want to display it.</p>\n"
},
{
"answer_id": 287880,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": false,
"text": "<p>When I am thinking about UI something like this is comming to my mind.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kBAqU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBAqU.png\" alt=\"enter image description here\"></a></p>\n\n<p>Something similar has YouTube under the video.</p>\n\n<p>When user fills input and clicks enter or submit button to create list, you will send ajax request with list name and save it as a record in <code>wp_usermeta</code> table with <code>meta_key</code> <code>_list_user_1</code> and <code>meta_value</code> as list title.</p>\n\n<p>To add post to this list you have to save record in <code>wp_postmeta</code> table with <code>_list_post_1</code> value in <code>meta_key</code> field and value of <code>umeta_id</code> from <code>_list_user_1</code> row in field <code>meta_value</code>.</p>\n\n<p><code>wp_usermeta</code></p>\n\n<pre><code>+----------+---------+--------------+------------+\n| umeta_id | user_id | meta_key | meta_value |\n+----------+---------+--------------+------------+\n| 100 | 1 | _list_user_1 | List 1 |\n+----------+---------+--------------+------------+\n</code></pre>\n\n<p><code>wp_postmeta</code></p>\n\n<pre><code>+---------+---------+--------------+------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+--------------+------------+\n| 1 | 1 | _list_post_1 | 100 |\n+---------+---------+--------------+------------+\n</code></pre>\n\n<p>To get all lists for user:</p>\n\n<pre><code>SELECT *\nFROM `wp_usermeta`\nWHERE `user_id` = 1\n AND `meta_key` LIKE \"_list_user_%\";\n</code></pre>\n\n<p>To get all posts for List 1:</p>\n\n<pre><code>SELECT *\nFROM `wp_posts`\nINNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)\nWHERE wp_postmeta.`meta_key` LIKE \"_list_post_%\"\n AND wp_postmeta.`meta_value` = 100;\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287857",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123092/"
] |
I am not asking you to write the all code or asking a plugin, I am asking a way to build this feature because I don't have any plan in my mind to build this feature.
This is the requirement : There are many posts on the website. Logged Users (Front-end users) should have a feature to save list of posts.
Ex :
* List 01 : My favorite Posts
* List 02 : Blogging related posts
* List 03 : Watch later Posts
I want user to allow to create these types of list. Then they can add any number of posts. And these list are private. I mean only created user can access the list.
**This is something like we label emails on gmail.**
What can I use to save list? I have no idea what can I use for it... At least is this possible with WordPress?
|
I'd suggest using using custom tables to keep things lean.
Have two tables: A table of lists and a table of posts and which lists they belong to.
The lists table (let's call it `wp_lists`) would look like:
```
+----+---------+----------------+
| id | user_id | name |
+----+---------+----------------+
| 1 | 2 | My list |
| 2 | 2 | My second list |
+----+---------+----------------+
```
You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.
And the lists-posts table (let's call it `wp_post_list`) would look like:
```
+---------+---------+
| post_id | list_id |
+---------+---------+
| 2 | 2 |
| 3 | 2 |
| 2 | 1 |
+---------+---------+
```
Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the `post_id`/`list_id` combinations should all be unique, since posts can't be in a list more than once.
So when someone creates a list you'd insert it into `wp_lists`. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.
To get the lists that belong to the current user you'd just query `wp_lists` based on the `user_id` column.
When someone adds a post to a list you'd insert the post ID into `wp_post_list` alongside the list it belongs to. When you want to see all posts within a list you'd query based on the `list_id` column, then put the resulting IDs into a `WP_Query` or `get_posts()`.
When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query `wp_post_list` based on the `post_id`, but `JOIN` it to `wp_lists` and limit results to ones with lists that have the current user's ID.
|
287,858 |
<p>everytime I analyze free wordpress.org theme, I am not able to find how the css file is linked in the theme. as far as i learned css file should be linked in <code>header.php</code> using link tag. but everytime I check themes I didn't see any code in which they link their css through link tag. check example of this theme <code>header.php</code> <a href="https://imgur.com/a/EwSe7" rel="nofollow noreferrer">https://imgur.com/a/EwSe7</a>. my question is how they are linking their file, if its not showing in <code>header.php</code>?</p>
|
[
{
"answer_id": 287877,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest using using custom tables to keep things lean.</p>\n\n<p>Have two tables: A table of lists and a table of posts and which lists they belong to. </p>\n\n<p>The lists table (let's call it <code>wp_lists</code>) would look like:</p>\n\n<pre><code>+----+---------+----------------+\n| id | user_id | name |\n+----+---------+----------------+\n| 1 | 2 | My list |\n| 2 | 2 | My second list |\n+----+---------+----------------+\n</code></pre>\n\n<p>You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.</p>\n\n<p>And the lists-posts table (let's call it <code>wp_post_list</code>) would look like:</p>\n\n<pre><code>+---------+---------+\n| post_id | list_id |\n+---------+---------+\n| 2 | 2 |\n| 3 | 2 |\n| 2 | 1 |\n+---------+---------+\n</code></pre>\n\n<p>Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the <code>post_id</code>/<code>list_id</code> combinations should all be unique, since posts can't be in a list more than once. </p>\n\n<p>So when someone creates a list you'd insert it into <code>wp_lists</code>. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.</p>\n\n<p>To get the lists that belong to the current user you'd just query <code>wp_lists</code> based on the <code>user_id</code> column.</p>\n\n<p>When someone adds a post to a list you'd insert the post ID into <code>wp_post_list</code> alongside the list it belongs to. When you want to see all posts within a list you'd query based on the <code>list_id</code> column, then put the resulting IDs into a <code>WP_Query</code> or <code>get_posts()</code>.</p>\n\n<p>When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query <code>wp_post_list</code> based on the <code>post_id</code>, but <code>JOIN</code> it to <code>wp_lists</code> and limit results to ones with lists that have the current user's ID.</p>\n"
},
{
"answer_id": 287879,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a button on the front and save the ID of the currently displayed post in user's meta. Here's a simple way to do this:</p>\n\n<h2>Output a Button on Front</h2>\n\n<p>You need to create a button in your <code>single.php</code> ( or whatever page you want ) to allow the user to actually set the post as a favorite. The below template does this. The <code>like-overlay</code> class is used to create a loading effect while the request is being processed.</p>\n\n<pre><code><div id=\"like-button\" class=\"like btn btn-default\" type=\"button\">\n <span class=\"fa fa-heart\"></span>\n <span class=\"like-overlay\"><i class=\"fa fa-spin fa-circle-o-notch\"></i></span>\n</div>\n<input type=\"hidden\" value=\"<?php the_ID(); ?>\" id=\"current-post-id\"/>\n<input type=\"hidden\" value=\"<?php echo get_current_user_id(); ?>\" id=\"current-user-id\"/>\n</code></pre>\n\n<h2>Add a Click event to the Button</h2>\n\n<p>When the user clicks the button, send an AJAX request to the server, and update the button based on the results. You might need to localize the script to pass the rest URL and other data.</p>\n\n<pre><code>$('#like-button').on('click',function (e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: 'http://example.com/wp-json/my_route/v1/ajax_favorite',\n data: { post_id: $('#current-post-id').val(), user_id : $('#current-user-id').val() },\n beforeSend: function() {\n $('#like-button').addClass('active').prop('disabled', true);\n },\n success: function(data){\n\n $('#like-button').removeClass('active').prop('disabled', false);\n\n if( data != null ){\n\n if( data == '400' ) {\n $('#like-button').removeClass('selected');\n } else if( data == '200') {\n $('#like-button').addClass('selected');\n }\n }\n },\n error:function(){\n\n }\n });\n});\n</code></pre>\n\n<h2>Process the Ajax Request Using REST-API</h2>\n\n<p>Now create a rest route and process the data. If the received post ID doesn't exists in the user meta, add it and return a successful code. If it does, remove it and let your script know about it.</p>\n\n<pre><code>add_action( 'rest_api_init', 'my_rest_routes');\nfunction my_rest_routes() {\n // Path to ajax like function\n register_rest_route(\n 'my_route/v1',\n '/ajax_favorite/',\n array(\n 'methods' => 'GET',\n 'callback' => 'ajax_favorite'\n )\n );\n}\n\nfunction ajax_favorite(){\n\n // If the ID is not set, return\n if(!isset($_GET['post_id']) || !isset($_GET['user_id'])){\n return $data['status'] = '500';\n }\n\n // Store user and product's ID\n $post_id = sanitize_text_field($_GET['post_id']);\n $user_id = sanitize_text_field($_GET['user_id']);\n $user_meta = get_user_meta($user_id,'_favorite_posts',false);\n\n // Check if the post is favorited or not\n if( in_array( $post_id, $user_meta ) ){\n delete_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '400';\n } else {\n add_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '200';\n }\n\n}\n</code></pre>\n\n<p>You can use this as a template to output any button that saves data from front-end to database. Don't forget to sanitize the data, and use nonce too.</p>\n\n<p>Now of course all you need is to get the <code>_favorite_posts</code> user meta whenever you want to display it.</p>\n"
},
{
"answer_id": 287880,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": false,
"text": "<p>When I am thinking about UI something like this is comming to my mind.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kBAqU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBAqU.png\" alt=\"enter image description here\"></a></p>\n\n<p>Something similar has YouTube under the video.</p>\n\n<p>When user fills input and clicks enter or submit button to create list, you will send ajax request with list name and save it as a record in <code>wp_usermeta</code> table with <code>meta_key</code> <code>_list_user_1</code> and <code>meta_value</code> as list title.</p>\n\n<p>To add post to this list you have to save record in <code>wp_postmeta</code> table with <code>_list_post_1</code> value in <code>meta_key</code> field and value of <code>umeta_id</code> from <code>_list_user_1</code> row in field <code>meta_value</code>.</p>\n\n<p><code>wp_usermeta</code></p>\n\n<pre><code>+----------+---------+--------------+------------+\n| umeta_id | user_id | meta_key | meta_value |\n+----------+---------+--------------+------------+\n| 100 | 1 | _list_user_1 | List 1 |\n+----------+---------+--------------+------------+\n</code></pre>\n\n<p><code>wp_postmeta</code></p>\n\n<pre><code>+---------+---------+--------------+------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+--------------+------------+\n| 1 | 1 | _list_post_1 | 100 |\n+---------+---------+--------------+------------+\n</code></pre>\n\n<p>To get all lists for user:</p>\n\n<pre><code>SELECT *\nFROM `wp_usermeta`\nWHERE `user_id` = 1\n AND `meta_key` LIKE \"_list_user_%\";\n</code></pre>\n\n<p>To get all posts for List 1:</p>\n\n<pre><code>SELECT *\nFROM `wp_posts`\nINNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)\nWHERE wp_postmeta.`meta_key` LIKE \"_list_post_%\"\n AND wp_postmeta.`meta_value` = 100;\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130750/"
] |
everytime I analyze free wordpress.org theme, I am not able to find how the css file is linked in the theme. as far as i learned css file should be linked in `header.php` using link tag. but everytime I check themes I didn't see any code in which they link their css through link tag. check example of this theme `header.php` <https://imgur.com/a/EwSe7>. my question is how they are linking their file, if its not showing in `header.php`?
|
I'd suggest using using custom tables to keep things lean.
Have two tables: A table of lists and a table of posts and which lists they belong to.
The lists table (let's call it `wp_lists`) would look like:
```
+----+---------+----------------+
| id | user_id | name |
+----+---------+----------------+
| 1 | 2 | My list |
| 2 | 2 | My second list |
+----+---------+----------------+
```
You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.
And the lists-posts table (let's call it `wp_post_list`) would look like:
```
+---------+---------+
| post_id | list_id |
+---------+---------+
| 2 | 2 |
| 3 | 2 |
| 2 | 1 |
+---------+---------+
```
Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the `post_id`/`list_id` combinations should all be unique, since posts can't be in a list more than once.
So when someone creates a list you'd insert it into `wp_lists`. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.
To get the lists that belong to the current user you'd just query `wp_lists` based on the `user_id` column.
When someone adds a post to a list you'd insert the post ID into `wp_post_list` alongside the list it belongs to. When you want to see all posts within a list you'd query based on the `list_id` column, then put the resulting IDs into a `WP_Query` or `get_posts()`.
When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query `wp_post_list` based on the `post_id`, but `JOIN` it to `wp_lists` and limit results to ones with lists that have the current user's ID.
|
287,863 |
<p>I've been trying to create my own slider for my blog posts recently but I cannot get it to work. I have tried different code online but none of them rotate my list items(These are created by the post loop). Below is code I tried from <a href="https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_rr" rel="nofollow noreferrer">W3Schools</a> but it shows an error <strong>Uncaught TypeError: Cannot read property 'style' of undefined at carousel</strong></p>
<p>Here is my function from functions.php which I call on index.php to display the posts:</p>
<pre><code>function displayBlogSlider() {
$args = array(
'posts_per_page' => 3
);
// the query
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<div class="slider js--slider">
<!-- pagination here -->
<ul class="slider-inner js--slider-inner">
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="slider-item js--slider-item">
<div class="slider-info">
<?php blog_set_featured_background(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p>By <a href="<?php the_author(); ?>"><?php the_author(); ?></a></p>
<p><?php the_date(); ?> &mdash; <a href="#"><?php comments_number(); ?></a> &#9679; <a href="#"><?php the_category(); ?></a></p>
</div>
</li>
<?php endwhile; ?>
</ul>
<!-- end of the loop -->
<div class="slider-nav">
<a href="#" class="nav-prev js--nav-prev">&lt;</a>
<a href="#" class="nav-next js--nav-next">&gt;</a>
</div>
</div>
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;
}
function blog_set_featured_background() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full, false );
if ($image_url[0]) {
?>
<style>
.slider-inner {
height:100%;
margin:0!important;
}
.slider-inner {
background: linear-gradient( rgba(0, 0, 0, 0.20), rgba(0, 0, 0, 0.80)), url(<?php echo $image_url[0]; ?>) #000 no-repeat;
background-position: center;
background-size: cover;
}
</style>
<?php
}
}
</code></pre>
<p>And here is my javascript for making the list items rotate(similar to W3S):</p>
<pre><code>var myIndex = 0;
carousel();
function carousel() {
var i;
var listItem = document.getElementsByClassName("js--slider-item");
for(i = 0; i < listItem.length; i++) {
listItem[i].style.display = "none";
}
myIndex++;
if(myIndex > listItem.length) {
myIndex = 1;
}
listItem[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
</code></pre>
<p>If there is a better way of making a carousel for wordpress blog posts, I'll accept all advice and info. <strong>But</strong> I want to create it myself, I don't want to make use of a plugin. Also, I'd prefer pure javascript since I am still learning it.</p>
<p>I want to create something similar to the first slider here - <a href="https://manohara.incredibbble.com/" rel="nofollow noreferrer">https://manohara.incredibbble.com/</a></p>
|
[
{
"answer_id": 287877,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest using using custom tables to keep things lean.</p>\n\n<p>Have two tables: A table of lists and a table of posts and which lists they belong to. </p>\n\n<p>The lists table (let's call it <code>wp_lists</code>) would look like:</p>\n\n<pre><code>+----+---------+----------------+\n| id | user_id | name |\n+----+---------+----------------+\n| 1 | 2 | My list |\n| 2 | 2 | My second list |\n+----+---------+----------------+\n</code></pre>\n\n<p>You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.</p>\n\n<p>And the lists-posts table (let's call it <code>wp_post_list</code>) would look like:</p>\n\n<pre><code>+---------+---------+\n| post_id | list_id |\n+---------+---------+\n| 2 | 2 |\n| 3 | 2 |\n| 2 | 1 |\n+---------+---------+\n</code></pre>\n\n<p>Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the <code>post_id</code>/<code>list_id</code> combinations should all be unique, since posts can't be in a list more than once. </p>\n\n<p>So when someone creates a list you'd insert it into <code>wp_lists</code>. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.</p>\n\n<p>To get the lists that belong to the current user you'd just query <code>wp_lists</code> based on the <code>user_id</code> column.</p>\n\n<p>When someone adds a post to a list you'd insert the post ID into <code>wp_post_list</code> alongside the list it belongs to. When you want to see all posts within a list you'd query based on the <code>list_id</code> column, then put the resulting IDs into a <code>WP_Query</code> or <code>get_posts()</code>.</p>\n\n<p>When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query <code>wp_post_list</code> based on the <code>post_id</code>, but <code>JOIN</code> it to <code>wp_lists</code> and limit results to ones with lists that have the current user's ID.</p>\n"
},
{
"answer_id": 287879,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a button on the front and save the ID of the currently displayed post in user's meta. Here's a simple way to do this:</p>\n\n<h2>Output a Button on Front</h2>\n\n<p>You need to create a button in your <code>single.php</code> ( or whatever page you want ) to allow the user to actually set the post as a favorite. The below template does this. The <code>like-overlay</code> class is used to create a loading effect while the request is being processed.</p>\n\n<pre><code><div id=\"like-button\" class=\"like btn btn-default\" type=\"button\">\n <span class=\"fa fa-heart\"></span>\n <span class=\"like-overlay\"><i class=\"fa fa-spin fa-circle-o-notch\"></i></span>\n</div>\n<input type=\"hidden\" value=\"<?php the_ID(); ?>\" id=\"current-post-id\"/>\n<input type=\"hidden\" value=\"<?php echo get_current_user_id(); ?>\" id=\"current-user-id\"/>\n</code></pre>\n\n<h2>Add a Click event to the Button</h2>\n\n<p>When the user clicks the button, send an AJAX request to the server, and update the button based on the results. You might need to localize the script to pass the rest URL and other data.</p>\n\n<pre><code>$('#like-button').on('click',function (e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: 'http://example.com/wp-json/my_route/v1/ajax_favorite',\n data: { post_id: $('#current-post-id').val(), user_id : $('#current-user-id').val() },\n beforeSend: function() {\n $('#like-button').addClass('active').prop('disabled', true);\n },\n success: function(data){\n\n $('#like-button').removeClass('active').prop('disabled', false);\n\n if( data != null ){\n\n if( data == '400' ) {\n $('#like-button').removeClass('selected');\n } else if( data == '200') {\n $('#like-button').addClass('selected');\n }\n }\n },\n error:function(){\n\n }\n });\n});\n</code></pre>\n\n<h2>Process the Ajax Request Using REST-API</h2>\n\n<p>Now create a rest route and process the data. If the received post ID doesn't exists in the user meta, add it and return a successful code. If it does, remove it and let your script know about it.</p>\n\n<pre><code>add_action( 'rest_api_init', 'my_rest_routes');\nfunction my_rest_routes() {\n // Path to ajax like function\n register_rest_route(\n 'my_route/v1',\n '/ajax_favorite/',\n array(\n 'methods' => 'GET',\n 'callback' => 'ajax_favorite'\n )\n );\n}\n\nfunction ajax_favorite(){\n\n // If the ID is not set, return\n if(!isset($_GET['post_id']) || !isset($_GET['user_id'])){\n return $data['status'] = '500';\n }\n\n // Store user and product's ID\n $post_id = sanitize_text_field($_GET['post_id']);\n $user_id = sanitize_text_field($_GET['user_id']);\n $user_meta = get_user_meta($user_id,'_favorite_posts',false);\n\n // Check if the post is favorited or not\n if( in_array( $post_id, $user_meta ) ){\n delete_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '400';\n } else {\n add_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '200';\n }\n\n}\n</code></pre>\n\n<p>You can use this as a template to output any button that saves data from front-end to database. Don't forget to sanitize the data, and use nonce too.</p>\n\n<p>Now of course all you need is to get the <code>_favorite_posts</code> user meta whenever you want to display it.</p>\n"
},
{
"answer_id": 287880,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": false,
"text": "<p>When I am thinking about UI something like this is comming to my mind.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kBAqU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBAqU.png\" alt=\"enter image description here\"></a></p>\n\n<p>Something similar has YouTube under the video.</p>\n\n<p>When user fills input and clicks enter or submit button to create list, you will send ajax request with list name and save it as a record in <code>wp_usermeta</code> table with <code>meta_key</code> <code>_list_user_1</code> and <code>meta_value</code> as list title.</p>\n\n<p>To add post to this list you have to save record in <code>wp_postmeta</code> table with <code>_list_post_1</code> value in <code>meta_key</code> field and value of <code>umeta_id</code> from <code>_list_user_1</code> row in field <code>meta_value</code>.</p>\n\n<p><code>wp_usermeta</code></p>\n\n<pre><code>+----------+---------+--------------+------------+\n| umeta_id | user_id | meta_key | meta_value |\n+----------+---------+--------------+------------+\n| 100 | 1 | _list_user_1 | List 1 |\n+----------+---------+--------------+------------+\n</code></pre>\n\n<p><code>wp_postmeta</code></p>\n\n<pre><code>+---------+---------+--------------+------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+--------------+------------+\n| 1 | 1 | _list_post_1 | 100 |\n+---------+---------+--------------+------------+\n</code></pre>\n\n<p>To get all lists for user:</p>\n\n<pre><code>SELECT *\nFROM `wp_usermeta`\nWHERE `user_id` = 1\n AND `meta_key` LIKE \"_list_user_%\";\n</code></pre>\n\n<p>To get all posts for List 1:</p>\n\n<pre><code>SELECT *\nFROM `wp_posts`\nINNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)\nWHERE wp_postmeta.`meta_key` LIKE \"_list_post_%\"\n AND wp_postmeta.`meta_value` = 100;\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287863",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130103/"
] |
I've been trying to create my own slider for my blog posts recently but I cannot get it to work. I have tried different code online but none of them rotate my list items(These are created by the post loop). Below is code I tried from [W3Schools](https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_rr) but it shows an error **Uncaught TypeError: Cannot read property 'style' of undefined at carousel**
Here is my function from functions.php which I call on index.php to display the posts:
```
function displayBlogSlider() {
$args = array(
'posts_per_page' => 3
);
// the query
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<div class="slider js--slider">
<!-- pagination here -->
<ul class="slider-inner js--slider-inner">
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li class="slider-item js--slider-item">
<div class="slider-info">
<?php blog_set_featured_background(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p>By <a href="<?php the_author(); ?>"><?php the_author(); ?></a></p>
<p><?php the_date(); ?> — <a href="#"><?php comments_number(); ?></a> ● <a href="#"><?php the_category(); ?></a></p>
</div>
</li>
<?php endwhile; ?>
</ul>
<!-- end of the loop -->
<div class="slider-nav">
<a href="#" class="nav-prev js--nav-prev"><</a>
<a href="#" class="nav-next js--nav-next">></a>
</div>
</div>
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif;
}
function blog_set_featured_background() {
$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full, false );
if ($image_url[0]) {
?>
<style>
.slider-inner {
height:100%;
margin:0!important;
}
.slider-inner {
background: linear-gradient( rgba(0, 0, 0, 0.20), rgba(0, 0, 0, 0.80)), url(<?php echo $image_url[0]; ?>) #000 no-repeat;
background-position: center;
background-size: cover;
}
</style>
<?php
}
}
```
And here is my javascript for making the list items rotate(similar to W3S):
```
var myIndex = 0;
carousel();
function carousel() {
var i;
var listItem = document.getElementsByClassName("js--slider-item");
for(i = 0; i < listItem.length; i++) {
listItem[i].style.display = "none";
}
myIndex++;
if(myIndex > listItem.length) {
myIndex = 1;
}
listItem[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}
```
If there is a better way of making a carousel for wordpress blog posts, I'll accept all advice and info. **But** I want to create it myself, I don't want to make use of a plugin. Also, I'd prefer pure javascript since I am still learning it.
I want to create something similar to the first slider here - <https://manohara.incredibbble.com/>
|
I'd suggest using using custom tables to keep things lean.
Have two tables: A table of lists and a table of posts and which lists they belong to.
The lists table (let's call it `wp_lists`) would look like:
```
+----+---------+----------------+
| id | user_id | name |
+----+---------+----------------+
| 1 | 2 | My list |
| 2 | 2 | My second list |
+----+---------+----------------+
```
You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.
And the lists-posts table (let's call it `wp_post_list`) would look like:
```
+---------+---------+
| post_id | list_id |
+---------+---------+
| 2 | 2 |
| 3 | 2 |
| 2 | 1 |
+---------+---------+
```
Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the `post_id`/`list_id` combinations should all be unique, since posts can't be in a list more than once.
So when someone creates a list you'd insert it into `wp_lists`. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.
To get the lists that belong to the current user you'd just query `wp_lists` based on the `user_id` column.
When someone adds a post to a list you'd insert the post ID into `wp_post_list` alongside the list it belongs to. When you want to see all posts within a list you'd query based on the `list_id` column, then put the resulting IDs into a `WP_Query` or `get_posts()`.
When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query `wp_post_list` based on the `post_id`, but `JOIN` it to `wp_lists` and limit results to ones with lists that have the current user's ID.
|
287,884 |
<p>I wonder if you can help me track down why all my images are being cropped to a 300px size that I've not specified anywhere at all. I know from some digging in the past that WordPress introduced a default size of 768px and basically hid it from us, now I'm wondering if they (or WooCommerce - this is a WooCommerce site) also have a hidden size of 300px.</p>
<p>That 768px size was called <code>medium_large</code> and you would unset it like so:</p>
<pre><code>function mytheme_filter_image_sizes($sizes) {
unset( $sizes[ 'medium_large' ] );
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'mytheme_filter_image_sizes' );
</code></pre>
<p>Has anyone come across this extra 300px image and how did you unset it? Googling this has proved useless.</p>
<p>Here's my code for the image sizes being used in this theme:</p>
<pre><code>add_theme_support( 'post-thumbnails' );
// Set our preferred default image sizes
set_post_thumbnail_size( 960, 960, true );
update_option( 'thumbnail_size_w', 240 );
update_option( 'thumbnail_size_h', 240 );
update_option( 'thumbnail_crop', 1 );
update_option( 'medium_size_w', 720 );
update_option( 'medium_size_h', 720 );
update_option( 'large_size_w', 1440 );
update_option( 'large_size_h', 1440 );
// Custom new sizes for the srcset
add_image_size( 'mytheme-hd-img', 1920, 1920);
add_image_size( 'mytheme-epic-img', 2400, 2400);
</code></pre>
<p>And for WooCommerece:</p>
<pre><code>$catalog = array(
'width' => '360',
'height' => '360',
'crop' => 1 // true
);
$single = array(
'width' => '720',
'height' => '720',
'crop' => 0 // false
);
$thumbnail = array(
'width' => '240',
'height' => '240',
'crop' => 1 // true
);
// Image sizes
update_option( 'shop_catalog_image_size', $catalog );
update_option( 'shop_single_image_size', $single );
update_option( 'shop_thumbnail_image_size', $thumbnail );
</code></pre>
|
[
{
"answer_id": 287877,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>I'd suggest using using custom tables to keep things lean.</p>\n\n<p>Have two tables: A table of lists and a table of posts and which lists they belong to. </p>\n\n<p>The lists table (let's call it <code>wp_lists</code>) would look like:</p>\n\n<pre><code>+----+---------+----------------+\n| id | user_id | name |\n+----+---------+----------------+\n| 1 | 2 | My list |\n| 2 | 2 | My second list |\n+----+---------+----------------+\n</code></pre>\n\n<p>You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.</p>\n\n<p>And the lists-posts table (let's call it <code>wp_post_list</code>) would look like:</p>\n\n<pre><code>+---------+---------+\n| post_id | list_id |\n+---------+---------+\n| 2 | 2 |\n| 3 | 2 |\n| 2 | 1 |\n+---------+---------+\n</code></pre>\n\n<p>Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the <code>post_id</code>/<code>list_id</code> combinations should all be unique, since posts can't be in a list more than once. </p>\n\n<p>So when someone creates a list you'd insert it into <code>wp_lists</code>. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.</p>\n\n<p>To get the lists that belong to the current user you'd just query <code>wp_lists</code> based on the <code>user_id</code> column.</p>\n\n<p>When someone adds a post to a list you'd insert the post ID into <code>wp_post_list</code> alongside the list it belongs to. When you want to see all posts within a list you'd query based on the <code>list_id</code> column, then put the resulting IDs into a <code>WP_Query</code> or <code>get_posts()</code>.</p>\n\n<p>When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query <code>wp_post_list</code> based on the <code>post_id</code>, but <code>JOIN</code> it to <code>wp_lists</code> and limit results to ones with lists that have the current user's ID.</p>\n"
},
{
"answer_id": 287879,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a button on the front and save the ID of the currently displayed post in user's meta. Here's a simple way to do this:</p>\n\n<h2>Output a Button on Front</h2>\n\n<p>You need to create a button in your <code>single.php</code> ( or whatever page you want ) to allow the user to actually set the post as a favorite. The below template does this. The <code>like-overlay</code> class is used to create a loading effect while the request is being processed.</p>\n\n<pre><code><div id=\"like-button\" class=\"like btn btn-default\" type=\"button\">\n <span class=\"fa fa-heart\"></span>\n <span class=\"like-overlay\"><i class=\"fa fa-spin fa-circle-o-notch\"></i></span>\n</div>\n<input type=\"hidden\" value=\"<?php the_ID(); ?>\" id=\"current-post-id\"/>\n<input type=\"hidden\" value=\"<?php echo get_current_user_id(); ?>\" id=\"current-user-id\"/>\n</code></pre>\n\n<h2>Add a Click event to the Button</h2>\n\n<p>When the user clicks the button, send an AJAX request to the server, and update the button based on the results. You might need to localize the script to pass the rest URL and other data.</p>\n\n<pre><code>$('#like-button').on('click',function (e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: 'http://example.com/wp-json/my_route/v1/ajax_favorite',\n data: { post_id: $('#current-post-id').val(), user_id : $('#current-user-id').val() },\n beforeSend: function() {\n $('#like-button').addClass('active').prop('disabled', true);\n },\n success: function(data){\n\n $('#like-button').removeClass('active').prop('disabled', false);\n\n if( data != null ){\n\n if( data == '400' ) {\n $('#like-button').removeClass('selected');\n } else if( data == '200') {\n $('#like-button').addClass('selected');\n }\n }\n },\n error:function(){\n\n }\n });\n});\n</code></pre>\n\n<h2>Process the Ajax Request Using REST-API</h2>\n\n<p>Now create a rest route and process the data. If the received post ID doesn't exists in the user meta, add it and return a successful code. If it does, remove it and let your script know about it.</p>\n\n<pre><code>add_action( 'rest_api_init', 'my_rest_routes');\nfunction my_rest_routes() {\n // Path to ajax like function\n register_rest_route(\n 'my_route/v1',\n '/ajax_favorite/',\n array(\n 'methods' => 'GET',\n 'callback' => 'ajax_favorite'\n )\n );\n}\n\nfunction ajax_favorite(){\n\n // If the ID is not set, return\n if(!isset($_GET['post_id']) || !isset($_GET['user_id'])){\n return $data['status'] = '500';\n }\n\n // Store user and product's ID\n $post_id = sanitize_text_field($_GET['post_id']);\n $user_id = sanitize_text_field($_GET['user_id']);\n $user_meta = get_user_meta($user_id,'_favorite_posts',false);\n\n // Check if the post is favorited or not\n if( in_array( $post_id, $user_meta ) ){\n delete_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '400';\n } else {\n add_user_meta($user_id,'_favorite_posts',$post_id);\n return $data['status'] = '200';\n }\n\n}\n</code></pre>\n\n<p>You can use this as a template to output any button that saves data from front-end to database. Don't forget to sanitize the data, and use nonce too.</p>\n\n<p>Now of course all you need is to get the <code>_favorite_posts</code> user meta whenever you want to display it.</p>\n"
},
{
"answer_id": 287880,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": false,
"text": "<p>When I am thinking about UI something like this is comming to my mind.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kBAqU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBAqU.png\" alt=\"enter image description here\"></a></p>\n\n<p>Something similar has YouTube under the video.</p>\n\n<p>When user fills input and clicks enter or submit button to create list, you will send ajax request with list name and save it as a record in <code>wp_usermeta</code> table with <code>meta_key</code> <code>_list_user_1</code> and <code>meta_value</code> as list title.</p>\n\n<p>To add post to this list you have to save record in <code>wp_postmeta</code> table with <code>_list_post_1</code> value in <code>meta_key</code> field and value of <code>umeta_id</code> from <code>_list_user_1</code> row in field <code>meta_value</code>.</p>\n\n<p><code>wp_usermeta</code></p>\n\n<pre><code>+----------+---------+--------------+------------+\n| umeta_id | user_id | meta_key | meta_value |\n+----------+---------+--------------+------------+\n| 100 | 1 | _list_user_1 | List 1 |\n+----------+---------+--------------+------------+\n</code></pre>\n\n<p><code>wp_postmeta</code></p>\n\n<pre><code>+---------+---------+--------------+------------+\n| meta_id | post_id | meta_key | meta_value |\n+---------+---------+--------------+------------+\n| 1 | 1 | _list_post_1 | 100 |\n+---------+---------+--------------+------------+\n</code></pre>\n\n<p>To get all lists for user:</p>\n\n<pre><code>SELECT *\nFROM `wp_usermeta`\nWHERE `user_id` = 1\n AND `meta_key` LIKE \"_list_user_%\";\n</code></pre>\n\n<p>To get all posts for List 1:</p>\n\n<pre><code>SELECT *\nFROM `wp_posts`\nINNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)\nWHERE wp_postmeta.`meta_key` LIKE \"_list_post_%\"\n AND wp_postmeta.`meta_value` = 100;\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287884",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119546/"
] |
I wonder if you can help me track down why all my images are being cropped to a 300px size that I've not specified anywhere at all. I know from some digging in the past that WordPress introduced a default size of 768px and basically hid it from us, now I'm wondering if they (or WooCommerce - this is a WooCommerce site) also have a hidden size of 300px.
That 768px size was called `medium_large` and you would unset it like so:
```
function mytheme_filter_image_sizes($sizes) {
unset( $sizes[ 'medium_large' ] );
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'mytheme_filter_image_sizes' );
```
Has anyone come across this extra 300px image and how did you unset it? Googling this has proved useless.
Here's my code for the image sizes being used in this theme:
```
add_theme_support( 'post-thumbnails' );
// Set our preferred default image sizes
set_post_thumbnail_size( 960, 960, true );
update_option( 'thumbnail_size_w', 240 );
update_option( 'thumbnail_size_h', 240 );
update_option( 'thumbnail_crop', 1 );
update_option( 'medium_size_w', 720 );
update_option( 'medium_size_h', 720 );
update_option( 'large_size_w', 1440 );
update_option( 'large_size_h', 1440 );
// Custom new sizes for the srcset
add_image_size( 'mytheme-hd-img', 1920, 1920);
add_image_size( 'mytheme-epic-img', 2400, 2400);
```
And for WooCommerece:
```
$catalog = array(
'width' => '360',
'height' => '360',
'crop' => 1 // true
);
$single = array(
'width' => '720',
'height' => '720',
'crop' => 0 // false
);
$thumbnail = array(
'width' => '240',
'height' => '240',
'crop' => 1 // true
);
// Image sizes
update_option( 'shop_catalog_image_size', $catalog );
update_option( 'shop_single_image_size', $single );
update_option( 'shop_thumbnail_image_size', $thumbnail );
```
|
I'd suggest using using custom tables to keep things lean.
Have two tables: A table of lists and a table of posts and which lists they belong to.
The lists table (let's call it `wp_lists`) would look like:
```
+----+---------+----------------+
| id | user_id | name |
+----+---------+----------------+
| 1 | 2 | My list |
| 2 | 2 | My second list |
+----+---------+----------------+
```
You could have more columns here if lists had more data to them, like a description or associated colour. If the table starts growing you might want to split it into a two tables, with a separate table for user-list relationships.
And the lists-posts table (let's call it `wp_post_list`) would look like:
```
+---------+---------+
| post_id | list_id |
+---------+---------+
| 2 | 2 |
| 3 | 2 |
| 2 | 1 |
+---------+---------+
```
Maybe you'd want an ID column, but I'm not sure what you'd need it for, since the `post_id`/`list_id` combinations should all be unique, since posts can't be in a list more than once.
So when someone creates a list you'd insert it into `wp_lists`. They could create as many as they like, or you could limit it in PHP by checking how many they've already got.
To get the lists that belong to the current user you'd just query `wp_lists` based on the `user_id` column.
When someone adds a post to a list you'd insert the post ID into `wp_post_list` alongside the list it belongs to. When you want to see all posts within a list you'd query based on the `list_id` column, then put the resulting IDs into a `WP_Query` or `get_posts()`.
When browsing posts you'd want to show which of the user's lists it already belongs too. In that case you'd query `wp_post_list` based on the `post_id`, but `JOIN` it to `wp_lists` and limit results to ones with lists that have the current user's ID.
|
287,886 |
<p>I'm using the following code to select products with the following post_metas:</p>
<p>_product_new, _product_almost_new, _product_old</p>
<pre><code>add_action( 'woocommerce_product_query', 'custom_vtp_shop_order' );
function custom_vtp_shop_order($q){
if ( ! $q->is_main_query() ) return;
if (! is_admin() && (is_shop() || is_archive) ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'Sold', 'Service' ),
'operator' => 'NOT IN'
)));
$q->set('meta_query', array(array(
'relation' => 'OR',
'product_new' => array(
'key' => '_product_new',
'value' => '1',
),
'product_almost_new' => array(
'key' => '_product_almost_new',
'value' => '1',
),
'product_old' => array(
'key' => '_product_old',
'value' => '1',
)
)));
/*THIS HAS NO EFFECT*/
$q->set('orderby', array(array(
'product_new' => 'DESC',
'product_old' => 'DESC',
'product_almost_new' => 'DESC',
)
));
}
}
</code></pre>
<p>I want the products to then be displayed in the following order:</p>
<ol>
<li>product_new</li>
<li>product_old</li>
<li>product_almost_new</li>
</ol>
<p>I am using $q->set('orderby', array(......) but this is having no effect. My products are ALWAYS being ordered product_old, product_almost_new, product_new.</p>
<p>Any ideas why my 'orderby' is not working? Thanks in advance for any help!</p>
|
[
{
"answer_id": 287895,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>With <code>WP_Query</code> it's only possible to sort by a single meta value by setting the <code>meta_key</code> argument to which key you want to be able to sort by, and <code>orderby</code> to <code>meta_value</code> (or <code>meta_value_num</code> if the value is to be sorted numerically).</p>\n\n<p>This is what the arguments would look like:</p>\n\n<pre><code>$args = array(\n 'meta_key' => '_product_new',\n 'orderby' => 'meta_value_num',\n 'meta_query' = array(\n 'relation' => 'OR',\n array(\n 'key' => '_product_new',\n 'value' => '1',\n ),\n array(\n 'key' => '_product_almost_new',\n 'value' => '1',\n ), \n array(\n 'key' => '_product_old',\n 'value' => '1',\n )\n )\n);\n</code></pre>\n\n<p>That will query all posts that have <code>_product_new</code>, <code>_product_almost_new</code>, or <code>_product_old</code>, and order them so that the ones with <code>_product_new</code> will be at the top or bottom (depending on <code>order</code>).</p>\n\n<p>The problem is that this will only sort by one meta value, <code>_product_new</code>, and ignore the others. But this is just a limitation of <code>WP_Query</code>. <em>It's not possible to sort results by multiple meta values.</em></p>\n\n<p>A potential solution is to have a single meta key, say <code>_product_age</code>, and set it to a numerical value that represents each of the states you want to sort by. So instead of having <code>_product_new</code> as a boolean, set <code>_product_age</code> to <code>1</code>, instead of <code>_product_almost_new</code>, set <code>_product_age</code> to <code>3</code>, and instead of <code>_product_old</code>, set <code>_product_age</code> to <code>2</code>.</p>\n\n<p>Then you could use these args to sort the way you want;</p>\n\n<pre><code>$args = array(\n 'meta_key' => '_product_age',\n 'orderby' => 'meta_value_num',\n 'order' => 'ASC',\n 'meta_query' = array(\n array(\n 'key' => '_product_age',\n 'value' => array( 1, 2, 3 ),\n 'compare' => 'IN',\n ),\n )\n);\n</code></pre>\n"
},
{
"answer_id": 341615,
"author": "Sharpey",
"author_id": 154800,
"author_profile": "https://wordpress.stackexchange.com/users/154800",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is old but here is the possible solution:</p>\n\n<pre><code>$q->set('orderby', 'product_new product_old product_almost_new');\n$q->set('order', 'DESC');\n\n</code></pre>\n\n<p>So just try to pass parameters as a string in required order.</p>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84924/"
] |
I'm using the following code to select products with the following post\_metas:
\_product\_new, \_product\_almost\_new, \_product\_old
```
add_action( 'woocommerce_product_query', 'custom_vtp_shop_order' );
function custom_vtp_shop_order($q){
if ( ! $q->is_main_query() ) return;
if (! is_admin() && (is_shop() || is_archive) ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'Sold', 'Service' ),
'operator' => 'NOT IN'
)));
$q->set('meta_query', array(array(
'relation' => 'OR',
'product_new' => array(
'key' => '_product_new',
'value' => '1',
),
'product_almost_new' => array(
'key' => '_product_almost_new',
'value' => '1',
),
'product_old' => array(
'key' => '_product_old',
'value' => '1',
)
)));
/*THIS HAS NO EFFECT*/
$q->set('orderby', array(array(
'product_new' => 'DESC',
'product_old' => 'DESC',
'product_almost_new' => 'DESC',
)
));
}
}
```
I want the products to then be displayed in the following order:
1. product\_new
2. product\_old
3. product\_almost\_new
I am using $q->set('orderby', array(......) but this is having no effect. My products are ALWAYS being ordered product\_old, product\_almost\_new, product\_new.
Any ideas why my 'orderby' is not working? Thanks in advance for any help!
|
With `WP_Query` it's only possible to sort by a single meta value by setting the `meta_key` argument to which key you want to be able to sort by, and `orderby` to `meta_value` (or `meta_value_num` if the value is to be sorted numerically).
This is what the arguments would look like:
```
$args = array(
'meta_key' => '_product_new',
'orderby' => 'meta_value_num',
'meta_query' = array(
'relation' => 'OR',
array(
'key' => '_product_new',
'value' => '1',
),
array(
'key' => '_product_almost_new',
'value' => '1',
),
array(
'key' => '_product_old',
'value' => '1',
)
)
);
```
That will query all posts that have `_product_new`, `_product_almost_new`, or `_product_old`, and order them so that the ones with `_product_new` will be at the top or bottom (depending on `order`).
The problem is that this will only sort by one meta value, `_product_new`, and ignore the others. But this is just a limitation of `WP_Query`. *It's not possible to sort results by multiple meta values.*
A potential solution is to have a single meta key, say `_product_age`, and set it to a numerical value that represents each of the states you want to sort by. So instead of having `_product_new` as a boolean, set `_product_age` to `1`, instead of `_product_almost_new`, set `_product_age` to `3`, and instead of `_product_old`, set `_product_age` to `2`.
Then you could use these args to sort the way you want;
```
$args = array(
'meta_key' => '_product_age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' = array(
array(
'key' => '_product_age',
'value' => array( 1, 2, 3 ),
'compare' => 'IN',
),
)
);
```
|
287,893 |
<p>I'm using Contact Form 7 with an ACF field.</p>
<p>In ACF, I created an email field : <code>email</code>.</p>
<p>In my Contact Form 7, I have a field called <code>destination-email</code>:
<br/><code>[email* destination-email id:exp-email default:shortcode_attr]</code></p>
<p>In my template file i have a line :</p>
<pre class="lang-php prettyprint-override"><code><?php echo do_shortcode( '[contact-form-7 id="983" title="Formulaire de contact 1" destination-email="[email protected]"]' ); ?>
</code></pre>
<p>I need to replace "[email protected]" with the value of the ACF field <code>email</code>.</p>
<p>How can I do it?</p>
|
[
{
"answer_id": 288012,
"author": "Wilco",
"author_id": 102737,
"author_profile": "https://wordpress.stackexchange.com/users/102737",
"pm_score": 3,
"selected": true,
"text": "<p>You can use php values inside the do_shortcode function\nIn your case it will be like this:</p>\n\n<pre><code><?php echo do_shortcode( '[contact-form-7 id=\"983\" title=\"Formulaire de contact 1\" destination-email=\"'.get_field( 'email' ).'\"]' ); ?>\n</code></pre>\n"
},
{
"answer_id": 387335,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>In addition, the field can be populated with the help of post meta</p>\n<pre><code>[email* destination-email id:exp-email default:default:post_meta ]\n</code></pre>\n<p>destination-email = ACF field id.\ninstead of email, a hidden field can be used. (in case it is being used just for fetching recipient email address.)</p>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132818/"
] |
I'm using Contact Form 7 with an ACF field.
In ACF, I created an email field : `email`.
In my Contact Form 7, I have a field called `destination-email`:
`[email* destination-email id:exp-email default:shortcode_attr]`
In my template file i have a line :
```php
<?php echo do_shortcode( '[contact-form-7 id="983" title="Formulaire de contact 1" destination-email="[email protected]"]' ); ?>
```
I need to replace "[email protected]" with the value of the ACF field `email`.
How can I do it?
|
You can use php values inside the do\_shortcode function
In your case it will be like this:
```
<?php echo do_shortcode( '[contact-form-7 id="983" title="Formulaire de contact 1" destination-email="'.get_field( 'email' ).'"]' ); ?>
```
|
287,909 |
<p>I am trying to customise my Wordpress homepage. </p>
<p>I decided to get fullscreen image theme (TwoFold by Fuel Themes).
As I am preparing photography portfolio website, graphic content is very important to me.
However, I'd like to add some text below the image slider, ideally it would be a whole page below the current homepage slider.
Please see the demo theme: <a href="http://twofold.fuelthemes.net" rel="nofollow noreferrer">TwoFold Theme</a> </p>
<p>And what I would like to add (simple mockup):</p>
<p><a href="https://i.stack.imgur.com/SmWFI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SmWFI.jpg" alt="Desired layout"></a></p>
<p>Methods I found here seem not to work well - they extend bottom of the homepage, however return no content below the slider. </p>
<p>Let's say I'd like to insert "About" page under the slider. How should I modify home page layout to do that? </p>
<p>Orignal code below:</p>
<pre><code><?php
/*
Template Name: Home
*/
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$id = get_the_ID();
$home_layout = get_post_meta($id, 'home_layout', true) ? get_post_meta($id, 'home_layout', true) : 'style1';
get_template_part( 'inc/templates/homepage/'.$home_layout );
?>
<?php endwhile; else : endif; ?>
<?php get_footer(); ?>
</code></pre>
<p>Lots of thanks for any hints as I am clueless. </p>
|
[
{
"answer_id": 288012,
"author": "Wilco",
"author_id": 102737,
"author_profile": "https://wordpress.stackexchange.com/users/102737",
"pm_score": 3,
"selected": true,
"text": "<p>You can use php values inside the do_shortcode function\nIn your case it will be like this:</p>\n\n<pre><code><?php echo do_shortcode( '[contact-form-7 id=\"983\" title=\"Formulaire de contact 1\" destination-email=\"'.get_field( 'email' ).'\"]' ); ?>\n</code></pre>\n"
},
{
"answer_id": 387335,
"author": "MMK",
"author_id": 148207,
"author_profile": "https://wordpress.stackexchange.com/users/148207",
"pm_score": 0,
"selected": false,
"text": "<p>In addition, the field can be populated with the help of post meta</p>\n<pre><code>[email* destination-email id:exp-email default:default:post_meta ]\n</code></pre>\n<p>destination-email = ACF field id.\ninstead of email, a hidden field can be used. (in case it is being used just for fetching recipient email address.)</p>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287909",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132829/"
] |
I am trying to customise my Wordpress homepage.
I decided to get fullscreen image theme (TwoFold by Fuel Themes).
As I am preparing photography portfolio website, graphic content is very important to me.
However, I'd like to add some text below the image slider, ideally it would be a whole page below the current homepage slider.
Please see the demo theme: [TwoFold Theme](http://twofold.fuelthemes.net)
And what I would like to add (simple mockup):
[](https://i.stack.imgur.com/SmWFI.jpg)
Methods I found here seem not to work well - they extend bottom of the homepage, however return no content below the slider.
Let's say I'd like to insert "About" page under the slider. How should I modify home page layout to do that?
Orignal code below:
```
<?php
/*
Template Name: Home
*/
?>
<?php get_header(); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$id = get_the_ID();
$home_layout = get_post_meta($id, 'home_layout', true) ? get_post_meta($id, 'home_layout', true) : 'style1';
get_template_part( 'inc/templates/homepage/'.$home_layout );
?>
<?php endwhile; else : endif; ?>
<?php get_footer(); ?>
```
Lots of thanks for any hints as I am clueless.
|
You can use php values inside the do\_shortcode function
In your case it will be like this:
```
<?php echo do_shortcode( '[contact-form-7 id="983" title="Formulaire de contact 1" destination-email="'.get_field( 'email' ).'"]' ); ?>
```
|
287,930 |
<p>I have 2 post types, one is for my posts and the other one is used as a submission form. </p>
<p>When a user is on a single post page for post type A, I am trying to do several checks to then display content - </p>
<p>1) I'm checking if the user is logged in</p>
<p>2) if he has published any posts (submitted forms) in post type B </p>
<p>3) If so is custom field (1) in authors published posts in post type B empty or not </p>
<p>4) If its not empty, does the value match the value of custom field (2) of any posts in post type A that is currently being viewed</p>
<p>This is what I have so far ---</p>
<pre><code><?php
$user = wp_get_current_user();
$user_id = get_current_user_id();
$balance = mycred_get_users_balance( $user_id, 'piq_credits' );
if( (is_user_logged_in()) && (piq_user_has_posts($user->ID)) && ($balance != '0') ) { ?>
</code></pre>
<p>The piq_user_has_posts function is --</p>
<pre><code>function piq_user_has_posts($user_id) {
$result = new WP_Query(array(
'author'=>$user_id,
'post_type'=>'post_type_b',
'post_status'=>'publish',
'posts_per_page'=>1,
));
return (count($result->posts)!=0);
}
</code></pre>
<p>What I need now is to be able to check - <strong>if $customfield1 = $customfield2 then do something</strong> </p>
<p>Again, each custom field is from a different post type and Im doing this on a single post page for one of those post types.</p>
<p>So far I tried the following --</p>
<pre><code>$users_query = new WP_Query( array(
'post_type' => 'piq_request',
'meta_key' => 'piq_link',
'meta_value' => $piq_link,
) );
//echo $piq_link;
echo $this_property_id;
if($piq_link == $this_property_id) {
</code></pre>
|
[
{
"answer_id": 287914,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": true,
"text": "<p>There are several different forms of PayPal. It sounds like you are using PayPal Standard, which always takes the visitor to PayPal's website to process the payment.</p>\n\n<p>There are a couple of different PayPal Pro type accounts where you can have the visitor fill out a single form, including their payment information <em>if</em> they are using a credit or debit card, and the form will both save to the WP database and process the payment with PayPal as the gateway. However, these accounts also require that you allow PayPal <em>account</em> checkout as a second option, in which case the visitor fills out the form on your website but when they submit the form they are taken to PayPal's site to log in and complete the purchase. Since they are using a PayPal account, they just enter their email and password and don't have to re-type their address or other details. These Pro accounts do come at a monthly fee - you might want to call PayPal to discuss your options. Being a nonprofit, they will give you a discount on the fees they charge to process payments.</p>\n\n<p>I am not familiar enough with NinjaForms to know whether it integrates with these types of PayPal accounts. You might need to move to a different form system. Gravity Forms is one I know supports this type of payment, and I use it in the way described to receive donations and also capture the donors' contact information.</p>\n"
},
{
"answer_id": 287918,
"author": "Brent",
"author_id": 10972,
"author_profile": "https://wordpress.stackexchange.com/users/10972",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps look at flipping your work flow (right term?) so that they go to PayPal first, then after the donation has been made, go back to your website and verify their account details. We don't collect donations but we do use PayPal standard buttons for people to register on our website for online training.</p>\n\n<p>Our process is 1) make payment on PayPal (credit card or PayPal), then PayPal is able to send us back all the information that they already have collected (email and street address - most of the time) through their IPN relay process. We collect this in our database (albeit, it's a pretty customzied hack). </p>\n\n<p>It keeps visitors from having to enter data twice. </p>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] |
I have 2 post types, one is for my posts and the other one is used as a submission form.
When a user is on a single post page for post type A, I am trying to do several checks to then display content -
1) I'm checking if the user is logged in
2) if he has published any posts (submitted forms) in post type B
3) If so is custom field (1) in authors published posts in post type B empty or not
4) If its not empty, does the value match the value of custom field (2) of any posts in post type A that is currently being viewed
This is what I have so far ---
```
<?php
$user = wp_get_current_user();
$user_id = get_current_user_id();
$balance = mycred_get_users_balance( $user_id, 'piq_credits' );
if( (is_user_logged_in()) && (piq_user_has_posts($user->ID)) && ($balance != '0') ) { ?>
```
The piq\_user\_has\_posts function is --
```
function piq_user_has_posts($user_id) {
$result = new WP_Query(array(
'author'=>$user_id,
'post_type'=>'post_type_b',
'post_status'=>'publish',
'posts_per_page'=>1,
));
return (count($result->posts)!=0);
}
```
What I need now is to be able to check - **if $customfield1 = $customfield2 then do something**
Again, each custom field is from a different post type and Im doing this on a single post page for one of those post types.
So far I tried the following --
```
$users_query = new WP_Query( array(
'post_type' => 'piq_request',
'meta_key' => 'piq_link',
'meta_value' => $piq_link,
) );
//echo $piq_link;
echo $this_property_id;
if($piq_link == $this_property_id) {
```
|
There are several different forms of PayPal. It sounds like you are using PayPal Standard, which always takes the visitor to PayPal's website to process the payment.
There are a couple of different PayPal Pro type accounts where you can have the visitor fill out a single form, including their payment information *if* they are using a credit or debit card, and the form will both save to the WP database and process the payment with PayPal as the gateway. However, these accounts also require that you allow PayPal *account* checkout as a second option, in which case the visitor fills out the form on your website but when they submit the form they are taken to PayPal's site to log in and complete the purchase. Since they are using a PayPal account, they just enter their email and password and don't have to re-type their address or other details. These Pro accounts do come at a monthly fee - you might want to call PayPal to discuss your options. Being a nonprofit, they will give you a discount on the fees they charge to process payments.
I am not familiar enough with NinjaForms to know whether it integrates with these types of PayPal accounts. You might need to move to a different form system. Gravity Forms is one I know supports this type of payment, and I use it in the way described to receive donations and also capture the donors' contact information.
|
287,931 |
<p>I'm trying to get the category <strong>name</strong> instead of the <strong>ID</strong> from the WP REST API for my Custom Post Type. Some articles about endpoint modification gave me some ideas on how to solve it, but unfortunately i'm not getting it to work. This is my Code (* removed irrelevant code at some lines):</p>
<p><strong>CUSTOM POST TYPE</strong></p>
<pre><code><?php
add_action( 'init', 'portfolio_projects' );
function portfolio_projects() {
$labels = array([...]);
$args = array(
[...]
'show_in_rest' => true,
'rest_base' => 'projects',
'rest_controller_class' => 'Category_Data',
'supports' => array( 'title', 'thumbnail', 'editor'),
'taxonomies' => array('post_tag', 'category')
);
register_post_type( 'project', $args );
}
</code></pre>
<p><strong>CONTROLLER CLASS</strong></p>
<pre><code><?php
/**
* Category data
*/
class Category_Data extends WP_REST_Posts_Controller
{
public function init()
{
add_action('rest_api_init', array(
$this,
'add_category_data'
));
}
/**
* Add the category data
*/
public function add_category_data()
{
register_rest_field('project', 'category_data', ['get_callback' => array(
$this,
'get_all_category_data'
) , ]);
}
/**
* Get all the category data
*
* @param $object
* @param $field_name
* @param $request
*
* @return array
*/
public function get_all_category_data($object, $field_name, $request)
{
return get_the_category($object['id']);
}
}
</code></pre>
<p>I'd love to hear your ideas and thoughts on this.
Thanks</p>
|
[
{
"answer_id": 287933,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": false,
"text": "<p>This code will add <code>categories_names</code> field to wp rest api response:</p>\n\n<pre><code>function wpse_287931_register_categories_names_field() {\n\n register_rest_field( 'project',\n 'categories_names',\n array(\n 'get_callback' => 'wpse_287931_get_categories_names',\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n}\n\nadd_action( 'rest_api_init', 'wpse_287931_register_categories_names_field' );\n\nfunction wpse_287931_get_categories_names( $object, $field_name, $request ) {\n\n $formatted_categories = array();\n\n $categories = get_the_category( $object['id'] );\n\n foreach ($categories as $category) {\n $formatted_categories[] = $category->name;\n }\n\n return $formatted_categories;\n}\n</code></pre>\n"
},
{
"answer_id": 354802,
"author": "Adrián Benavente",
"author_id": 179894,
"author_profile": "https://wordpress.stackexchange.com/users/179894",
"pm_score": 3,
"selected": false,
"text": "<p>The same as above but replacing 'project' for <strong>array('post')</strong> should work.</p>\n<pre><code>function wpse_287931_register_categories_names_field()\n{\n register_rest_field(\n array('post'),\n 'categories_names',\n array(\n 'get_callback' => 'wpse_287931_get_categories_names',\n 'update_callback' => null,\n 'schema' => null,\n )\n );\n}\n\nadd_action('rest_api_init', 'wpse_287931_register_categories_names_field');\n\nfunction wpse_287931_get_categories_names($object, $field_name, $request)\n{\n $formatted_categories = array();\n\n $categories = get_the_category($object['id']);\n\n foreach ($categories as $category) {\n $formatted_categories[] = $category->name;\n }\n\n return $formatted_categories;\n}\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79865/"
] |
I'm trying to get the category **name** instead of the **ID** from the WP REST API for my Custom Post Type. Some articles about endpoint modification gave me some ideas on how to solve it, but unfortunately i'm not getting it to work. This is my Code (\* removed irrelevant code at some lines):
**CUSTOM POST TYPE**
```
<?php
add_action( 'init', 'portfolio_projects' );
function portfolio_projects() {
$labels = array([...]);
$args = array(
[...]
'show_in_rest' => true,
'rest_base' => 'projects',
'rest_controller_class' => 'Category_Data',
'supports' => array( 'title', 'thumbnail', 'editor'),
'taxonomies' => array('post_tag', 'category')
);
register_post_type( 'project', $args );
}
```
**CONTROLLER CLASS**
```
<?php
/**
* Category data
*/
class Category_Data extends WP_REST_Posts_Controller
{
public function init()
{
add_action('rest_api_init', array(
$this,
'add_category_data'
));
}
/**
* Add the category data
*/
public function add_category_data()
{
register_rest_field('project', 'category_data', ['get_callback' => array(
$this,
'get_all_category_data'
) , ]);
}
/**
* Get all the category data
*
* @param $object
* @param $field_name
* @param $request
*
* @return array
*/
public function get_all_category_data($object, $field_name, $request)
{
return get_the_category($object['id']);
}
}
```
I'd love to hear your ideas and thoughts on this.
Thanks
|
This code will add `categories_names` field to wp rest api response:
```
function wpse_287931_register_categories_names_field() {
register_rest_field( 'project',
'categories_names',
array(
'get_callback' => 'wpse_287931_get_categories_names',
'update_callback' => null,
'schema' => null,
)
);
}
add_action( 'rest_api_init', 'wpse_287931_register_categories_names_field' );
function wpse_287931_get_categories_names( $object, $field_name, $request ) {
$formatted_categories = array();
$categories = get_the_category( $object['id'] );
foreach ($categories as $category) {
$formatted_categories[] = $category->name;
}
return $formatted_categories;
}
```
|
287,946 |
<p>I've got a frontend form with text, select and checkbox inputs the text and selects update and work just fine, using update_post_meta() however the checkboxes aren't updating. Since they're stored in a serialized array do I need to use a different function or just set it up differently?</p>
<pre><code>update_post_meta($post_id, 'appliances', esc_attr(strip_tags($_POST['customMetaAppliances[]'])));
</code></pre>
<p>Here's the code to output the checkboxes on the frontend as well, which is working perfectly, its just that the checked options aren't saving to the database.</p>
<pre><code><?php
$allCheckbox = get_field('appliances'); //Checked value from backend
$field_key = "field_5a0a1264370c0"; //Get value using key
$post_id = get_the_ID();
$field = get_field_object($field_key, $post_id);
$count = 0;
foreach($field['choices'] as $lab => $val){
if(is_array($allCheckbox) && in_array($val, $allCheckbox)){
$checked = 'checked = "checked"';
//$enable = '';
} else {
$checked = '';
//$enable = 'disabled=""';
}
?>
<li><input type="checkbox" name="customMetaAppliances[]" id="customMetaAppliances" value="<?php echo $lab; ?>" <?php echo $checked; ?> /><label><?php echo $val; ?></label></li>
<?php
$count++;
if ($count == 3) {
echo '</ul><ul class="propfeatures col span_6">';
$count = 0;
}
} ?>
</code></pre>
<p>When viewing the row within the database this is whats being passed, so the array of checkboxes is being ignored?</p>
<p><a href="https://i.stack.imgur.com/BRYoF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BRYoF.png" alt="enter image description here"></a></p>
<p><strong>UPDATE:</strong></p>
<p><a href="https://i.stack.imgur.com/3wtzP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wtzP.png" alt="enter image description here"></a></p>
<p>So this makes sense but it seems the array from name="customMetaAppliances[]" isn't being passed from the checkboxes? What do you guys think?</p>
|
[
{
"answer_id": 287948,
"author": "rzepak",
"author_id": 11897,
"author_profile": "https://wordpress.stackexchange.com/users/11897",
"pm_score": 0,
"selected": false,
"text": "<p>Shouldn't the name of the checkbox be name=\"customMetaAppliances[]\" ? That way you get an array of them in $_POST.\nnow you're passing just the value of last one in the form, if it's not checked it's empty, and not saved.</p>\n"
},
{
"answer_id": 288207,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": true,
"text": "<p>To be compatible with ACF you should first find out how ACF is saving checkboxes values to database. As I now this is serialized array. When we know that we must save our frontend checkboxes in the same way. The good news is you can pass only array to <code>update_post_meta</code> and WordPress will take care of serialization. </p>\n\n<p>The problem with your code is that you probably not passing array of checkbox values. You should investigate this part: <code>esc_attr(strip_tags($_POST['customMetaAppliances[]']))</code>.</p>\n\n<p>Two things which bother me here:</p>\n\n<ul>\n<li><code>esc_attr</code> and <code>strip_tags</code> functions are expecting string as argument not an array they may return unexpected results</li>\n<li>if you want to get array of checkboxes from post request you should use field name without square brackets <code>customMetaAppliances</code></li>\n</ul>\n\n<p>I think you can replace saving part with code:</p>\n\n<pre><code>$customMetaAppliances = filter_input( INPUT_POST, 'customMetaAppliances', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\nupdate_field( 'customMetaAppliances', $customMetaAppliances, $post_id );\n</code></pre>\n\n<p>Personaly when I have installed ACF I use <code>update_field</code> instead of <code>update_post_meta</code>.</p>\n\n<p>I created fully working class which will display form on the frontend after post content and save values to post ACF fields on submit.</p>\n\n<pre><code>class WPSE_287946_Form {\n\n /**\n * Class constructor\n */\n public function __construct() {\n\n $this->define_hooks();\n }\n\n public function save_form() {\n\n if( isset( $_POST['save'] ) ) { // Submit button\n\n $post_id = filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );\n $name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );\n $color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );\n $accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );\n\n update_field( 'name', $name, $post_id );\n update_field( 'color', $color, $post_id );\n update_field( 'accessories', $accessories, $post_id );\n\n // Redirect user because POST request on single post page will trigger 404 page.\n wp_redirect( get_permalink( $post_id ) );\n }\n }\n\n /**\n * Display form\n */\n public function display_form( $content ) {\n\n $name = get_field( 'name' );\n $color = get_field( 'color' );\n $accessories = get_field( 'accessories' );\n\n ob_start();\n\n ?>\n\n <form method=\"post\">\n <p>\n <?php $this->display_text( 'name', 'Name', $name ); ?>\n </p>\n <p>\n <?php $this->display_select( 'color', 'Color', $this->get_available_colors(), $color ); ?>\n </p>\n <p>\n <?php $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories ); ?>\n </p>\n <p>\n <input type=\"hidden\" name=\"id\" value=\"<?php esc_attr_e( get_the_ID() ) ?>\">\n <input type=\"submit\" name=\"save\" value=\"Submit\" />\n </p>\n </form>\n\n <?php\n\n $output = ob_get_contents();\n ob_end_clean();\n\n return $content . $output;\n }\n\n /**\n * Display text field\n */\n private function display_text( $name, $label, $value = '' ) {\n ?>\n <label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>\n <input type=\"text\" name=\"<?php esc_attr_e( $name ) ?>\" value=\"<?php esc_attr_e( $value ); ?>\">\n <?php\n }\n\n /**\n * Display select field\n */\n private function display_select( $name, $label, $options, $value = '' ) {\n ?>\n <label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>\n <select name=\"<?php esc_attr_e( $name ) ?>\">\n <?php $this->display_options( $options, $value ); ?>\n </select>\n <?php\n }\n\n /**\n * Display options\n */\n private function display_options( $options, $value ) {\n\n foreach( $options as $option_value => $option_label ):\n $selected = ( $option_value === $value ) ? ' selected' : '';\n ?>\n <option value=\"<?php esc_attr_e( $option_value ) ?>\"<?php esc_attr_e( $selected ) ?>><?php esc_html_e( $option_label, 'wpse_287946' ) ?></option>\n <?php\n\n endforeach;\n }\n\n /**\n * Display checkboxes field\n */\n private function display_checkboxes( $name, $label, $options, $values = array() ) {\n\n $name .= '[]';\n\n ?>\n <label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>\n <?php\n\n foreach ( $options as $option_value => $option_label ):\n $this->display_checkbox( $name, $option_label, $option_value, $values );\n endforeach;\n }\n\n /**\n * Display single checkbox field\n */\n private function display_checkbox( $name, $label, $available_value, $values = array() ) {\n $checked = ( in_array($available_value, $values) ) ? ' checked' : '';\n ?>\n <label>\n <input type=\"checkbox\" name=\"<?php esc_attr_e( $name ) ?>\" value=\"<?php esc_attr_e( $available_value ) ?>\"<?php esc_attr_e( $checked ) ?>>\n <?php esc_html_e( $label, 'wpse_287946' ) ?>\n </label>\n <?php\n }\n\n /**\n * Get available colors\n */\n private function get_available_colors() {\n\n return array(\n 'red' => 'Red',\n 'blue' => 'Blue',\n 'green' => 'Green',\n );\n }\n\n /**\n * Get available accessories\n */\n private function get_available_accessories() {\n\n return array(\n 'case' => 'Case',\n 'tempered_glass' => 'Tempered glass',\n 'headphones' => 'Headphones',\n );\n }\n\n /**\n * Define hooks related to plugin\n */\n private function define_hooks() {\n\n /**\n * Add action to save form\n */\n add_action( 'wp', array( $this, 'save_form' ) );\n\n /**\n * Add filter to display form\n */\n add_filter( 'the_content', array( $this, 'display_form' ) );\n }\n}\n\nnew WPSE_287946_Form();\n</code></pre>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51369/"
] |
I've got a frontend form with text, select and checkbox inputs the text and selects update and work just fine, using update\_post\_meta() however the checkboxes aren't updating. Since they're stored in a serialized array do I need to use a different function or just set it up differently?
```
update_post_meta($post_id, 'appliances', esc_attr(strip_tags($_POST['customMetaAppliances[]'])));
```
Here's the code to output the checkboxes on the frontend as well, which is working perfectly, its just that the checked options aren't saving to the database.
```
<?php
$allCheckbox = get_field('appliances'); //Checked value from backend
$field_key = "field_5a0a1264370c0"; //Get value using key
$post_id = get_the_ID();
$field = get_field_object($field_key, $post_id);
$count = 0;
foreach($field['choices'] as $lab => $val){
if(is_array($allCheckbox) && in_array($val, $allCheckbox)){
$checked = 'checked = "checked"';
//$enable = '';
} else {
$checked = '';
//$enable = 'disabled=""';
}
?>
<li><input type="checkbox" name="customMetaAppliances[]" id="customMetaAppliances" value="<?php echo $lab; ?>" <?php echo $checked; ?> /><label><?php echo $val; ?></label></li>
<?php
$count++;
if ($count == 3) {
echo '</ul><ul class="propfeatures col span_6">';
$count = 0;
}
} ?>
```
When viewing the row within the database this is whats being passed, so the array of checkboxes is being ignored?
[](https://i.stack.imgur.com/BRYoF.png)
**UPDATE:**
[](https://i.stack.imgur.com/3wtzP.png)
So this makes sense but it seems the array from name="customMetaAppliances[]" isn't being passed from the checkboxes? What do you guys think?
|
To be compatible with ACF you should first find out how ACF is saving checkboxes values to database. As I now this is serialized array. When we know that we must save our frontend checkboxes in the same way. The good news is you can pass only array to `update_post_meta` and WordPress will take care of serialization.
The problem with your code is that you probably not passing array of checkbox values. You should investigate this part: `esc_attr(strip_tags($_POST['customMetaAppliances[]']))`.
Two things which bother me here:
* `esc_attr` and `strip_tags` functions are expecting string as argument not an array they may return unexpected results
* if you want to get array of checkboxes from post request you should use field name without square brackets `customMetaAppliances`
I think you can replace saving part with code:
```
$customMetaAppliances = filter_input( INPUT_POST, 'customMetaAppliances', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
update_field( 'customMetaAppliances', $customMetaAppliances, $post_id );
```
Personaly when I have installed ACF I use `update_field` instead of `update_post_meta`.
I created fully working class which will display form on the frontend after post content and save values to post ACF fields on submit.
```
class WPSE_287946_Form {
/**
* Class constructor
*/
public function __construct() {
$this->define_hooks();
}
public function save_form() {
if( isset( $_POST['save'] ) ) { // Submit button
$post_id = filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
$name = filter_input( INPUT_POST, 'name', FILTER_SANITIZE_STRING );
$color = filter_input( INPUT_POST, 'color', FILTER_SANITIZE_STRING );
$accessories = filter_input( INPUT_POST, 'accessories', FILTER_SANITIZE_STRING, FILTER_REQUIRE_ARRAY );
update_field( 'name', $name, $post_id );
update_field( 'color', $color, $post_id );
update_field( 'accessories', $accessories, $post_id );
// Redirect user because POST request on single post page will trigger 404 page.
wp_redirect( get_permalink( $post_id ) );
}
}
/**
* Display form
*/
public function display_form( $content ) {
$name = get_field( 'name' );
$color = get_field( 'color' );
$accessories = get_field( 'accessories' );
ob_start();
?>
<form method="post">
<p>
<?php $this->display_text( 'name', 'Name', $name ); ?>
</p>
<p>
<?php $this->display_select( 'color', 'Color', $this->get_available_colors(), $color ); ?>
</p>
<p>
<?php $this->display_checkboxes( 'accessories', 'Accessories', $this->get_available_accessories(), $accessories ); ?>
</p>
<p>
<input type="hidden" name="id" value="<?php esc_attr_e( get_the_ID() ) ?>">
<input type="submit" name="save" value="Submit" />
</p>
</form>
<?php
$output = ob_get_contents();
ob_end_clean();
return $content . $output;
}
/**
* Display text field
*/
private function display_text( $name, $label, $value = '' ) {
?>
<label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>
<input type="text" name="<?php esc_attr_e( $name ) ?>" value="<?php esc_attr_e( $value ); ?>">
<?php
}
/**
* Display select field
*/
private function display_select( $name, $label, $options, $value = '' ) {
?>
<label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>
<select name="<?php esc_attr_e( $name ) ?>">
<?php $this->display_options( $options, $value ); ?>
</select>
<?php
}
/**
* Display options
*/
private function display_options( $options, $value ) {
foreach( $options as $option_value => $option_label ):
$selected = ( $option_value === $value ) ? ' selected' : '';
?>
<option value="<?php esc_attr_e( $option_value ) ?>"<?php esc_attr_e( $selected ) ?>><?php esc_html_e( $option_label, 'wpse_287946' ) ?></option>
<?php
endforeach;
}
/**
* Display checkboxes field
*/
private function display_checkboxes( $name, $label, $options, $values = array() ) {
$name .= '[]';
?>
<label><?php esc_html_e( $label, 'wpse_287946' ) ?></label>
<?php
foreach ( $options as $option_value => $option_label ):
$this->display_checkbox( $name, $option_label, $option_value, $values );
endforeach;
}
/**
* Display single checkbox field
*/
private function display_checkbox( $name, $label, $available_value, $values = array() ) {
$checked = ( in_array($available_value, $values) ) ? ' checked' : '';
?>
<label>
<input type="checkbox" name="<?php esc_attr_e( $name ) ?>" value="<?php esc_attr_e( $available_value ) ?>"<?php esc_attr_e( $checked ) ?>>
<?php esc_html_e( $label, 'wpse_287946' ) ?>
</label>
<?php
}
/**
* Get available colors
*/
private function get_available_colors() {
return array(
'red' => 'Red',
'blue' => 'Blue',
'green' => 'Green',
);
}
/**
* Get available accessories
*/
private function get_available_accessories() {
return array(
'case' => 'Case',
'tempered_glass' => 'Tempered glass',
'headphones' => 'Headphones',
);
}
/**
* Define hooks related to plugin
*/
private function define_hooks() {
/**
* Add action to save form
*/
add_action( 'wp', array( $this, 'save_form' ) );
/**
* Add filter to display form
*/
add_filter( 'the_content', array( $this, 'display_form' ) );
}
}
new WPSE_287946_Form();
```
|
287,952 |
<p>What is the default wp-content/uploads directory permission? What chmod command do I need to set it correctly?</p>
|
[
{
"answer_id": 287953,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 4,
"selected": true,
"text": "<p>You'll want directories to have 755 and files to have 644.\nyou can navigate to your www directory and use these 2 commands:</p>\n\n<pre><code>find . -type d -print0 | xargs -0 chmod 0755 # For directories\n</code></pre>\n\n<p>or</p>\n\n<pre><code>find . -type f -print0 | xargs -0 chmod 0644 # For files\n</code></pre>\n\n<p>(Obviously don't input the # or anything after it when using the above 2 commands)</p>\n"
},
{
"answer_id": 287966,
"author": "Anson W Han",
"author_id": 129547,
"author_profile": "https://wordpress.stackexchange.com/users/129547",
"pm_score": 2,
"selected": false,
"text": "<p>You can find a full list of recommended file and folder permissions on the codex at: <a href=\"https://codex.wordpress.org/Changing_File_Permissions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_File_Permissions</a> See the section entitled \"Using the Command Line\" for chmod commands.</p>\n\n<p>Otherwise, if you don't have shell access, you can also change permissions from an FTP client (outlined in codex page) or from the hosting provider's Cpanel > File Manager. (see <a href=\"https://www.siteground.com/tutorials/cpanel/file-permissions/\" rel=\"nofollow noreferrer\">https://www.siteground.com/tutorials/cpanel/file-permissions/</a> for how to edit file/folder permissions in File Manager within CPanel)</p>\n\n<p>In addition to the permission levels, you may need to check owner/group assigned to each file/folder. </p>\n\n<ul>\n<li><p>If you're on a shared hosting solution, chances are the default user account created for your CPanel access or similar web interface will have the proper group assignments when uploading files to run your Wordpress website.</p></li>\n<li><p>If you are on a more custom hosting package using root access, you will more than likely need to update the file/folder owner & group attributes (since the default apache user/www user is not the \"root\" account). Here's a link to a blog post with steps to determine what user apache is running as: <a href=\"https://www.cyberciti.biz/faq/unix-osx-linux-find-apache-user/\" rel=\"nofollow noreferrer\">https://www.cyberciti.biz/faq/unix-osx-linux-find-apache-user/</a><br>\nOnce you determine the user/group that apache runs as, you may need to use the chown command to recursively update owner/group to files/folders. </p></li>\n</ul>\n"
}
] |
2017/12/06
|
[
"https://wordpress.stackexchange.com/questions/287952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45709/"
] |
What is the default wp-content/uploads directory permission? What chmod command do I need to set it correctly?
|
You'll want directories to have 755 and files to have 644.
you can navigate to your www directory and use these 2 commands:
```
find . -type d -print0 | xargs -0 chmod 0755 # For directories
```
or
```
find . -type f -print0 | xargs -0 chmod 0644 # For files
```
(Obviously don't input the # or anything after it when using the above 2 commands)
|
287,973 |
<p>I tried different tests to make the home (a blog index, 3 latest posts) page use a different template than it's following generated paginated pages (blog.com/page/2). Essentially what I am trying to do is get my home page looking different with latest posts and the "Next Posts" links to the /page/2 with a different template. I thought this was common but can't seem to get it working.</p>
<p><strong>Test 1:</strong> </p>
<p>In Settings->Reading->Homepage Display I set to "Your latest posts". Created a 'home.php' file with <code>has_posts()</code> loop and pagination. <code>is_home()</code> and <code>is_front_page()</code> returns <strong>true</strong> on both the home page and its following paginated pages.</p>
<p><strong>Test 2:</strong></p>
<p>In Settings->Reading->Homepage Display, I set to "Static Page" and set it to a Page I created in the Pages section. Created a page-home.php template file it reads from. <code>is_home()</code> returns <strong>false</strong> and <code>is_front_page()</code> returns <strong>true</strong> on both the home page and its following paginated pages. </p>
<p><strong>Test 3:</strong></p>
<p>The obvious <code>page.php</code> template file didn't work.</p>
|
[
{
"answer_id": 287975,
"author": "Taj Khan",
"author_id": 128610,
"author_profile": "https://wordpress.stackexchange.com/users/128610",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/files/2014/10/wp-hierarchy.png\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/files/2014/10/wp-hierarchy.png</a></p>\n\n<p>should use archive template for this.</p>\n"
},
{
"answer_id": 287976,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 2,
"selected": true,
"text": "<p>You can use this:</p>\n\n<pre><code>$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n</code></pre>\n\n<p><code>$paged</code> will have the value 1 in you are or the first page or the value of respective pagination page number.</p>\n\n<p>Depending on this you can call <code>get_template_part()</code> to load the desired template for the page.</p>\n\n<p>Let me know if this helps.</p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/287973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132876/"
] |
I tried different tests to make the home (a blog index, 3 latest posts) page use a different template than it's following generated paginated pages (blog.com/page/2). Essentially what I am trying to do is get my home page looking different with latest posts and the "Next Posts" links to the /page/2 with a different template. I thought this was common but can't seem to get it working.
**Test 1:**
In Settings->Reading->Homepage Display I set to "Your latest posts". Created a 'home.php' file with `has_posts()` loop and pagination. `is_home()` and `is_front_page()` returns **true** on both the home page and its following paginated pages.
**Test 2:**
In Settings->Reading->Homepage Display, I set to "Static Page" and set it to a Page I created in the Pages section. Created a page-home.php template file it reads from. `is_home()` returns **false** and `is_front_page()` returns **true** on both the home page and its following paginated pages.
**Test 3:**
The obvious `page.php` template file didn't work.
|
You can use this:
```
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
```
`$paged` will have the value 1 in you are or the first page or the value of respective pagination page number.
Depending on this you can call `get_template_part()` to load the desired template for the page.
Let me know if this helps.
|
287,981 |
<p>I know there is connection between post table with term table but I am unable to figure it out. </p>
<p><code>wp_terms</code>, <code>wp_termmeta</code>, <code>wp_term_relationships</code> & <code>wp_term_taxonomy</code> relation is a little confusing. So, I am unable to write a query to get term id from post id.</p>
<p><strong>Actual Problem:</strong></p>
<p>I am using this piece of code to get an object and extract term id from that. But for some reasons, it is not working so I want to manually query in database to pull the term id and do rest of process.</p>
<pre><code>get_metadata_by_mid('post', $id);
</code></pre>
<p>it returns this object: (<strong>on local machine</strong>)</p>
<pre><code>stdClass Object
(
[meta_id] => 1268 //this id is passed to function like get_metadata_by_mid('post', 1268);
[post_id] => 222 //want to obtain this ID
[meta_key] => _menu_item_url
[meta_value] =>
)
</code></pre>
<p>Returns no result (<strong>on server</strong>) [so looking for alternative way]</p>
<p><strong>NOTE:</strong></p>
<ul>
<li><code>get_metadata_by_mid</code> works on local machine but doesn't work on live (i don't know, why whereas I have same version in both environment)</li>
<li>If someone can provide alternative way then it would be better than manual query.</li>
</ul>
|
[
{
"answer_id": 287983,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what you are trying to accomplish. </p>\n\n<p>It seems you are trying to get the terms associated to a post, but the function get_metadata_by_mid gets Metadata.</p>\n\n<p>If you are indeed trying to get all terms associated to a specific post, you can use the function <a href=\"https://developer.wordpress.org/reference/functions/wp_get_object_terms/\" rel=\"nofollow noreferrer\">wp_get_object_terms</a> or <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_post_terms\" rel=\"nofollow noreferrer\">wp_get_post_terms</a>.</p>\n\n<p>If you are trying to do something else, please restate your question to better explain what the intended result is ;)</p>\n"
},
{
"answer_id": 287985,
"author": "Quyen Nguyen",
"author_id": 132883,
"author_profile": "https://wordpress.stackexchange.com/users/132883",
"pm_score": 0,
"selected": false,
"text": "<p>the relationship of post and term you want is in table <code>wp_term_relasionship</code>.\nThe object id equal with <code>post_id</code>\nSo you can write your own query to access that</p>\n"
},
{
"answer_id": 287987,
"author": "Atlas_Gondal",
"author_id": 132879,
"author_profile": "https://wordpress.stackexchange.com/users/132879",
"pm_score": 3,
"selected": true,
"text": "<p>It is not good practice to use query when you have already builtin functions but for your need. </p>\n\n<p><strong>Try this solution</strong>:</p>\n\n<pre><code>global $wpdb;\n$meta = $wpdb->get_row( \"SELECT * FROM `wp_postmeta` WHERE `meta_id` = $id\" );\n\n//will return same object like returned by get_metadata_by_mid() function\nprint_r($meta);\n</code></pre>\n\n<p><strong>Debugging Technique:</strong></p>\n\n<p>As you mentioned, <code>get_metadata_by_mid()</code> isn't working on live server. I would say, </p>\n\n<ol>\n<li>Select any post id (for testing)</li>\n<li>Login to <code>phpmyadmin</code></li>\n<li><p>Run this search query</p>\n\n<pre><code>SELECT * FROM `wp_postmeta` WHERE `meta_id` = ID_GOES_HERE\n//copy post_id from the results\n</code></pre></li>\n<li><p>Run this query</p>\n\n<pre><code>SELECT * FROM `wp_terms` WHERE `term_id` = POST_ID_GOES_HERE\n</code></pre></li>\n</ol>\n\n<p>Try to match the process on both (local & live) server. Hopefully, it will help you identify problem.</p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/287981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132878/"
] |
I know there is connection between post table with term table but I am unable to figure it out.
`wp_terms`, `wp_termmeta`, `wp_term_relationships` & `wp_term_taxonomy` relation is a little confusing. So, I am unable to write a query to get term id from post id.
**Actual Problem:**
I am using this piece of code to get an object and extract term id from that. But for some reasons, it is not working so I want to manually query in database to pull the term id and do rest of process.
```
get_metadata_by_mid('post', $id);
```
it returns this object: (**on local machine**)
```
stdClass Object
(
[meta_id] => 1268 //this id is passed to function like get_metadata_by_mid('post', 1268);
[post_id] => 222 //want to obtain this ID
[meta_key] => _menu_item_url
[meta_value] =>
)
```
Returns no result (**on server**) [so looking for alternative way]
**NOTE:**
* `get_metadata_by_mid` works on local machine but doesn't work on live (i don't know, why whereas I have same version in both environment)
* If someone can provide alternative way then it would be better than manual query.
|
It is not good practice to use query when you have already builtin functions but for your need.
**Try this solution**:
```
global $wpdb;
$meta = $wpdb->get_row( "SELECT * FROM `wp_postmeta` WHERE `meta_id` = $id" );
//will return same object like returned by get_metadata_by_mid() function
print_r($meta);
```
**Debugging Technique:**
As you mentioned, `get_metadata_by_mid()` isn't working on live server. I would say,
1. Select any post id (for testing)
2. Login to `phpmyadmin`
3. Run this search query
```
SELECT * FROM `wp_postmeta` WHERE `meta_id` = ID_GOES_HERE
//copy post_id from the results
```
4. Run this query
```
SELECT * FROM `wp_terms` WHERE `term_id` = POST_ID_GOES_HERE
```
Try to match the process on both (local & live) server. Hopefully, it will help you identify problem.
|
287,988 |
<p>I usually use frameworks like Yii(2), Zend or Laravel to build pages but a customer forced us to use Wordpress this time.</p>
<p>I integrated Symfony/Twig as my template engine but now I have trouble with localization/translation. Because no matter what I do my strings won't be translated or even found by Wordpress.</p>
<p>Like in Laravel I created a Twig extension to translate the messages</p>
<pre><code>class TranslateExtension extends \Twig_Extension {
public function getFunctions(){
return array(
'__' => new \Twig_SimpleFunction('__', array($this, 'translate'))
);
}
public function getName(){
return 'TranslateExtension';
}
public function translate($string, $handle){
return __($string, $handle);
}
}
</code></pre>
<p>So I can do this in my template <code>{{ __('Some strings here', 'plugin-handle') }}</code>
but these are not translated or even found by <a href="https://wordpress.org/plugins/loco-translate/" rel="nofollow noreferrer">Loco translate</a> creating a custom entry in the <code>.po</code>file and compiling them into <code>.mo</code> files does not work either.</p>
<p>Can someone please explain me how this works? Nearly all answers/tutorials are about using POedit and insert the translations there but there are no "Add new translation" buttons and when I include the strings manually in my <code>.po</code> files and compile them WP still does not care about those.</p>
<p>If there is no way to use the WP method I'll include my custom functions to translate the strings without Wordpress</p>
<p><strong>Edit</strong><br>
Maybe someone can find my mistake when I provide some more information
This is how my po file looks like in <code>/languages/cardio-de_DE.po</code></p>
<pre><code>"Project-Id-Version: Cardio Plugin\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-11-30 16:19+0000\n"
"PO-Revision-Date: 2017-12-07 12:07+0100\n"
"Last-Translator: ******"
"Language-Team: German\n"
"Language: de_DE\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.5\n"
msgid "test"
msgstr "Fooo"
</code></pre>
<p>With <code>Poedit</code> I save the file and convert it to <code>.mo</code> format, then I upload it in the same directory like the <code>po</code> file<br>
In my template I do <code>{{ __("test", 'cardio') }}</code> which is returns basically <code>__("test", "cardio")</code> from php but the output is just <code>test</code> and not <code>Foo</code> as expected</p>
|
[
{
"answer_id": 287997,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>I have my own implementation of twig in WordPress as plugin and my translations are working. You can check my code.</p>\n\n<p>Keep in mind couple of things when when you will test the code:</p>\n\n<ul>\n<li>be sure that your WordPress have set <code>locale</code> which you want translate to</li>\n<li>be sure that you your <code>mo</code> file is compiled from newest version of <code>po</code> file</li>\n<li>be sure that your <code>mo</code> file exist and is loaded by <code>load_plugin_textdomain</code> function</li>\n</ul>\n\n<p>You can debug which translation files WordPress are loading using script below.</p>\n\n<pre><code>function wpse_287988_debug_mofiles( $mofile, $domain ) {\n\n var_dump($mofile);\n\n return $mofile;\n}\n\nadd_filter( 'load_textdomain_mofile', 'wpse_287988_debug_mofiles', 10, 2);\n\nfunction wpse_287988_terminate() {\n die();\n}\n\nadd_filter( 'wp_loaded', 'wpse_287988_terminate' );\n</code></pre>\n\n<p>Working twig implementation:</p>\n\n<pre><code>/**\n * Load composer autloader\n */\nrequire_once dirname(__FILE__) . '/vendor/autoload.php';\n\n// Main class\n\nclass WPSE_287988_Twig {\n\n /**\n * Templates path\n */\n private $templates_path;\n\n /**\n * Templates path\n */\n private $options;\n\n /**\n * Twig instance\n */\n private $twig;\n\n /**\n * Twig class constructor\n */\n public function __construct() {\n\n $this->templates_path = array();\n $this->options = array();\n\n $this->initialize_twig_options();\n $this->initialize_twig();\n $this->initialize_twig_functions();\n\n $this->define_hooks();\n }\n\n /**\n * Render method\n */\n public function render( $template, $variables = array() ) {\n\n return $this->twig->render( $template, $variables );\n }\n\n /**\n * Initialize twig options\n */\n private function initialize_twig_options() {\n\n /**\n * Resolve twig templates path\n */\n $plugins_dir = plugin_dir_path( __FILE__ );\n\n $this->templates_path[] = $plugins_dir;\n $this->templates_path[] = $plugins_dir . 'templates';\n\n foreach ($this->templates_path as $path) {\n\n if ( ! file_exists($path) ) {\n mkdir($path);\n }\n }\n\n /**\n * Resolve twig env options, disable cache\n */\n $this->options['cache'] = false;\n }\n\n /**\n * Initialize twig \n */\n private function initialize_twig() {\n\n $loader = new Twig_Loader_Filesystem( $this->templates_path );\n $this->twig = new Twig_Environment($loader, $this->options );\n }\n\n /**\n * Initialize additional twig funcitons\n */\n public function initialize_twig_functions() {\n\n /**\n * Add gettext __ functions to twig functions.\n */\n $function = new Twig_Function('__', '__');\n\n $this->twig->addFunction($function);\n }\n\n /**\n * Load the plugin translations\n */\n public function load_plugins_textdomain() {\n\n $textdomain = 'wpse_287988';\n\n load_plugin_textdomain( $textdomain, false, basename( dirname( __FILE__ ) ) . '/languages' );\n }\n\n /**\n * Define hooks required by twig class\n */\n private function define_hooks() {\n\n add_action( 'plugins_loaded', array( $this, 'load_plugins_textdomain' ) );\n }\n}\n\n// End of main class\n\n// Initialize class\n\nfunction wpse_287988_twig() {\n\n static $plugin;\n\n if ( isset( $plugin ) && $plugin instanceof WPSE_287988_Twig ) {\n return $plugin;\n }\n\n $plugin = new WPSE_287988_Twig();\n\n return $plugin;\n}\n\nwpse_287988_twig();\n\n// End of class initialization\n\n// Testing code\n\nfunction wpse_287988_test_render() {\n\n $twig = wpse_287988_twig();\n echo $twig->render('template.html.twig');\n\n die();\n}\n\nadd_action('init', 'wpse_287988_test_render');\n\n// End of testing code\n</code></pre>\n\n<p>My <code>template.html.twig</code> file:</p>\n\n<pre><code>{% set text = \"Foo\" %}\n\n{{ __(text, 'wpse_287988') }}\n</code></pre>\n\n<p>I keep my translations in languages directory in the main directory of my plugin. My translations files are named from textdomain and locale: <code>wpse_287988-pl_PL.po</code> and <code>wpse_287988-pl_PL.mo</code>.</p>\n"
},
{
"answer_id": 386219,
"author": "luukvhoudt",
"author_id": 44637,
"author_profile": "https://wordpress.stackexchange.com/users/44637",
"pm_score": 0,
"selected": false,
"text": "<p>Use a custom Twig filter.</p>\n<ol>\n<li>Create the filter for the WordPress <a href=\"https://developer.wordpress.org/reference/functions/__/\" rel=\"nofollow noreferrer\">gettext function (<code>__($text, $domain)</code>)</a>:\n<pre class=\"lang-php prettyprint-override\"><code>$wpGetText = new \\Twig\\TwigFilter('__', function ($text) {\n return __($text, 'my_domain');\n});\n</code></pre>\n</li>\n<li>Load the filter into your Twig environment:\n<pre class=\"lang-php prettyprint-override\"><code>$templateEngine = new \\Twig\\Environment($loader);\n$templateEngine->addFilter($wpGetText);\n</code></pre>\n</li>\n<li>Use the filter in your Twig template:\n<pre class=\"lang-html prettyprint-override\"><code><h1>{{ 'Hello World'|__ }}</h1>\n</code></pre>\n</li>\n</ol>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/287988",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132884/"
] |
I usually use frameworks like Yii(2), Zend or Laravel to build pages but a customer forced us to use Wordpress this time.
I integrated Symfony/Twig as my template engine but now I have trouble with localization/translation. Because no matter what I do my strings won't be translated or even found by Wordpress.
Like in Laravel I created a Twig extension to translate the messages
```
class TranslateExtension extends \Twig_Extension {
public function getFunctions(){
return array(
'__' => new \Twig_SimpleFunction('__', array($this, 'translate'))
);
}
public function getName(){
return 'TranslateExtension';
}
public function translate($string, $handle){
return __($string, $handle);
}
}
```
So I can do this in my template `{{ __('Some strings here', 'plugin-handle') }}`
but these are not translated or even found by [Loco translate](https://wordpress.org/plugins/loco-translate/) creating a custom entry in the `.po`file and compiling them into `.mo` files does not work either.
Can someone please explain me how this works? Nearly all answers/tutorials are about using POedit and insert the translations there but there are no "Add new translation" buttons and when I include the strings manually in my `.po` files and compile them WP still does not care about those.
If there is no way to use the WP method I'll include my custom functions to translate the strings without Wordpress
**Edit**
Maybe someone can find my mistake when I provide some more information
This is how my po file looks like in `/languages/cardio-de_DE.po`
```
"Project-Id-Version: Cardio Plugin\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-11-30 16:19+0000\n"
"PO-Revision-Date: 2017-12-07 12:07+0100\n"
"Last-Translator: ******"
"Language-Team: German\n"
"Language: de_DE\n"
"Plural-Forms: nplurals=2; plural=n != 1;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.5\n"
msgid "test"
msgstr "Fooo"
```
With `Poedit` I save the file and convert it to `.mo` format, then I upload it in the same directory like the `po` file
In my template I do `{{ __("test", 'cardio') }}` which is returns basically `__("test", "cardio")` from php but the output is just `test` and not `Foo` as expected
|
I have my own implementation of twig in WordPress as plugin and my translations are working. You can check my code.
Keep in mind couple of things when when you will test the code:
* be sure that your WordPress have set `locale` which you want translate to
* be sure that you your `mo` file is compiled from newest version of `po` file
* be sure that your `mo` file exist and is loaded by `load_plugin_textdomain` function
You can debug which translation files WordPress are loading using script below.
```
function wpse_287988_debug_mofiles( $mofile, $domain ) {
var_dump($mofile);
return $mofile;
}
add_filter( 'load_textdomain_mofile', 'wpse_287988_debug_mofiles', 10, 2);
function wpse_287988_terminate() {
die();
}
add_filter( 'wp_loaded', 'wpse_287988_terminate' );
```
Working twig implementation:
```
/**
* Load composer autloader
*/
require_once dirname(__FILE__) . '/vendor/autoload.php';
// Main class
class WPSE_287988_Twig {
/**
* Templates path
*/
private $templates_path;
/**
* Templates path
*/
private $options;
/**
* Twig instance
*/
private $twig;
/**
* Twig class constructor
*/
public function __construct() {
$this->templates_path = array();
$this->options = array();
$this->initialize_twig_options();
$this->initialize_twig();
$this->initialize_twig_functions();
$this->define_hooks();
}
/**
* Render method
*/
public function render( $template, $variables = array() ) {
return $this->twig->render( $template, $variables );
}
/**
* Initialize twig options
*/
private function initialize_twig_options() {
/**
* Resolve twig templates path
*/
$plugins_dir = plugin_dir_path( __FILE__ );
$this->templates_path[] = $plugins_dir;
$this->templates_path[] = $plugins_dir . 'templates';
foreach ($this->templates_path as $path) {
if ( ! file_exists($path) ) {
mkdir($path);
}
}
/**
* Resolve twig env options, disable cache
*/
$this->options['cache'] = false;
}
/**
* Initialize twig
*/
private function initialize_twig() {
$loader = new Twig_Loader_Filesystem( $this->templates_path );
$this->twig = new Twig_Environment($loader, $this->options );
}
/**
* Initialize additional twig funcitons
*/
public function initialize_twig_functions() {
/**
* Add gettext __ functions to twig functions.
*/
$function = new Twig_Function('__', '__');
$this->twig->addFunction($function);
}
/**
* Load the plugin translations
*/
public function load_plugins_textdomain() {
$textdomain = 'wpse_287988';
load_plugin_textdomain( $textdomain, false, basename( dirname( __FILE__ ) ) . '/languages' );
}
/**
* Define hooks required by twig class
*/
private function define_hooks() {
add_action( 'plugins_loaded', array( $this, 'load_plugins_textdomain' ) );
}
}
// End of main class
// Initialize class
function wpse_287988_twig() {
static $plugin;
if ( isset( $plugin ) && $plugin instanceof WPSE_287988_Twig ) {
return $plugin;
}
$plugin = new WPSE_287988_Twig();
return $plugin;
}
wpse_287988_twig();
// End of class initialization
// Testing code
function wpse_287988_test_render() {
$twig = wpse_287988_twig();
echo $twig->render('template.html.twig');
die();
}
add_action('init', 'wpse_287988_test_render');
// End of testing code
```
My `template.html.twig` file:
```
{% set text = "Foo" %}
{{ __(text, 'wpse_287988') }}
```
I keep my translations in languages directory in the main directory of my plugin. My translations files are named from textdomain and locale: `wpse_287988-pl_PL.po` and `wpse_287988-pl_PL.mo`.
|
287,990 |
<p>My custom post type & built in Wordpress blog posts SHARE the built in categories.</p>
<p>I have a piece of code that loops through and shows all (built in) categories that have posts assigned to them on 'archive-work.php'</p>
<p>I only want to show the categories that have CPT (work) posts assigned to them and NOT show any other posts (i.e. any blog posts that may be in the same category). However, my code below is showing all categories that have any post from any post type, how do I fix this to only show categories from the Work CPT?</p>
<pre><code><?php
$args=array(
'name' => 'category',
'public' => true,
'_builtin' => true
);
$output = 'names'; // or objects
$operator = 'and';
$taxonomies=get_taxonomies($args,$output,$operator);
if ($taxonomies) {
foreach ($taxonomies as $taxonomy ) {
$terms = get_terms([
'post_type' => array( 'work' ),
'taxonomy' => $taxonomy,
'hide_empty' => 1,
]);
foreach ( $terms as $term) {
if ($term->slug == 'all-articles') {} else {?>
<button class="filter--item" data-filter=".<?php echo $term->slug; ?>"><?php echo $term->name; ?> <span class="checkbox"><i class="i-check"></i></span></button>
<?php } } } } ?>
</code></pre>
|
[
{
"answer_id": 287997,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>I have my own implementation of twig in WordPress as plugin and my translations are working. You can check my code.</p>\n\n<p>Keep in mind couple of things when when you will test the code:</p>\n\n<ul>\n<li>be sure that your WordPress have set <code>locale</code> which you want translate to</li>\n<li>be sure that you your <code>mo</code> file is compiled from newest version of <code>po</code> file</li>\n<li>be sure that your <code>mo</code> file exist and is loaded by <code>load_plugin_textdomain</code> function</li>\n</ul>\n\n<p>You can debug which translation files WordPress are loading using script below.</p>\n\n<pre><code>function wpse_287988_debug_mofiles( $mofile, $domain ) {\n\n var_dump($mofile);\n\n return $mofile;\n}\n\nadd_filter( 'load_textdomain_mofile', 'wpse_287988_debug_mofiles', 10, 2);\n\nfunction wpse_287988_terminate() {\n die();\n}\n\nadd_filter( 'wp_loaded', 'wpse_287988_terminate' );\n</code></pre>\n\n<p>Working twig implementation:</p>\n\n<pre><code>/**\n * Load composer autloader\n */\nrequire_once dirname(__FILE__) . '/vendor/autoload.php';\n\n// Main class\n\nclass WPSE_287988_Twig {\n\n /**\n * Templates path\n */\n private $templates_path;\n\n /**\n * Templates path\n */\n private $options;\n\n /**\n * Twig instance\n */\n private $twig;\n\n /**\n * Twig class constructor\n */\n public function __construct() {\n\n $this->templates_path = array();\n $this->options = array();\n\n $this->initialize_twig_options();\n $this->initialize_twig();\n $this->initialize_twig_functions();\n\n $this->define_hooks();\n }\n\n /**\n * Render method\n */\n public function render( $template, $variables = array() ) {\n\n return $this->twig->render( $template, $variables );\n }\n\n /**\n * Initialize twig options\n */\n private function initialize_twig_options() {\n\n /**\n * Resolve twig templates path\n */\n $plugins_dir = plugin_dir_path( __FILE__ );\n\n $this->templates_path[] = $plugins_dir;\n $this->templates_path[] = $plugins_dir . 'templates';\n\n foreach ($this->templates_path as $path) {\n\n if ( ! file_exists($path) ) {\n mkdir($path);\n }\n }\n\n /**\n * Resolve twig env options, disable cache\n */\n $this->options['cache'] = false;\n }\n\n /**\n * Initialize twig \n */\n private function initialize_twig() {\n\n $loader = new Twig_Loader_Filesystem( $this->templates_path );\n $this->twig = new Twig_Environment($loader, $this->options );\n }\n\n /**\n * Initialize additional twig funcitons\n */\n public function initialize_twig_functions() {\n\n /**\n * Add gettext __ functions to twig functions.\n */\n $function = new Twig_Function('__', '__');\n\n $this->twig->addFunction($function);\n }\n\n /**\n * Load the plugin translations\n */\n public function load_plugins_textdomain() {\n\n $textdomain = 'wpse_287988';\n\n load_plugin_textdomain( $textdomain, false, basename( dirname( __FILE__ ) ) . '/languages' );\n }\n\n /**\n * Define hooks required by twig class\n */\n private function define_hooks() {\n\n add_action( 'plugins_loaded', array( $this, 'load_plugins_textdomain' ) );\n }\n}\n\n// End of main class\n\n// Initialize class\n\nfunction wpse_287988_twig() {\n\n static $plugin;\n\n if ( isset( $plugin ) && $plugin instanceof WPSE_287988_Twig ) {\n return $plugin;\n }\n\n $plugin = new WPSE_287988_Twig();\n\n return $plugin;\n}\n\nwpse_287988_twig();\n\n// End of class initialization\n\n// Testing code\n\nfunction wpse_287988_test_render() {\n\n $twig = wpse_287988_twig();\n echo $twig->render('template.html.twig');\n\n die();\n}\n\nadd_action('init', 'wpse_287988_test_render');\n\n// End of testing code\n</code></pre>\n\n<p>My <code>template.html.twig</code> file:</p>\n\n<pre><code>{% set text = \"Foo\" %}\n\n{{ __(text, 'wpse_287988') }}\n</code></pre>\n\n<p>I keep my translations in languages directory in the main directory of my plugin. My translations files are named from textdomain and locale: <code>wpse_287988-pl_PL.po</code> and <code>wpse_287988-pl_PL.mo</code>.</p>\n"
},
{
"answer_id": 386219,
"author": "luukvhoudt",
"author_id": 44637,
"author_profile": "https://wordpress.stackexchange.com/users/44637",
"pm_score": 0,
"selected": false,
"text": "<p>Use a custom Twig filter.</p>\n<ol>\n<li>Create the filter for the WordPress <a href=\"https://developer.wordpress.org/reference/functions/__/\" rel=\"nofollow noreferrer\">gettext function (<code>__($text, $domain)</code>)</a>:\n<pre class=\"lang-php prettyprint-override\"><code>$wpGetText = new \\Twig\\TwigFilter('__', function ($text) {\n return __($text, 'my_domain');\n});\n</code></pre>\n</li>\n<li>Load the filter into your Twig environment:\n<pre class=\"lang-php prettyprint-override\"><code>$templateEngine = new \\Twig\\Environment($loader);\n$templateEngine->addFilter($wpGetText);\n</code></pre>\n</li>\n<li>Use the filter in your Twig template:\n<pre class=\"lang-html prettyprint-override\"><code><h1>{{ 'Hello World'|__ }}</h1>\n</code></pre>\n</li>\n</ol>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/287990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14149/"
] |
My custom post type & built in Wordpress blog posts SHARE the built in categories.
I have a piece of code that loops through and shows all (built in) categories that have posts assigned to them on 'archive-work.php'
I only want to show the categories that have CPT (work) posts assigned to them and NOT show any other posts (i.e. any blog posts that may be in the same category). However, my code below is showing all categories that have any post from any post type, how do I fix this to only show categories from the Work CPT?
```
<?php
$args=array(
'name' => 'category',
'public' => true,
'_builtin' => true
);
$output = 'names'; // or objects
$operator = 'and';
$taxonomies=get_taxonomies($args,$output,$operator);
if ($taxonomies) {
foreach ($taxonomies as $taxonomy ) {
$terms = get_terms([
'post_type' => array( 'work' ),
'taxonomy' => $taxonomy,
'hide_empty' => 1,
]);
foreach ( $terms as $term) {
if ($term->slug == 'all-articles') {} else {?>
<button class="filter--item" data-filter=".<?php echo $term->slug; ?>"><?php echo $term->name; ?> <span class="checkbox"><i class="i-check"></i></span></button>
<?php } } } } ?>
```
|
I have my own implementation of twig in WordPress as plugin and my translations are working. You can check my code.
Keep in mind couple of things when when you will test the code:
* be sure that your WordPress have set `locale` which you want translate to
* be sure that you your `mo` file is compiled from newest version of `po` file
* be sure that your `mo` file exist and is loaded by `load_plugin_textdomain` function
You can debug which translation files WordPress are loading using script below.
```
function wpse_287988_debug_mofiles( $mofile, $domain ) {
var_dump($mofile);
return $mofile;
}
add_filter( 'load_textdomain_mofile', 'wpse_287988_debug_mofiles', 10, 2);
function wpse_287988_terminate() {
die();
}
add_filter( 'wp_loaded', 'wpse_287988_terminate' );
```
Working twig implementation:
```
/**
* Load composer autloader
*/
require_once dirname(__FILE__) . '/vendor/autoload.php';
// Main class
class WPSE_287988_Twig {
/**
* Templates path
*/
private $templates_path;
/**
* Templates path
*/
private $options;
/**
* Twig instance
*/
private $twig;
/**
* Twig class constructor
*/
public function __construct() {
$this->templates_path = array();
$this->options = array();
$this->initialize_twig_options();
$this->initialize_twig();
$this->initialize_twig_functions();
$this->define_hooks();
}
/**
* Render method
*/
public function render( $template, $variables = array() ) {
return $this->twig->render( $template, $variables );
}
/**
* Initialize twig options
*/
private function initialize_twig_options() {
/**
* Resolve twig templates path
*/
$plugins_dir = plugin_dir_path( __FILE__ );
$this->templates_path[] = $plugins_dir;
$this->templates_path[] = $plugins_dir . 'templates';
foreach ($this->templates_path as $path) {
if ( ! file_exists($path) ) {
mkdir($path);
}
}
/**
* Resolve twig env options, disable cache
*/
$this->options['cache'] = false;
}
/**
* Initialize twig
*/
private function initialize_twig() {
$loader = new Twig_Loader_Filesystem( $this->templates_path );
$this->twig = new Twig_Environment($loader, $this->options );
}
/**
* Initialize additional twig funcitons
*/
public function initialize_twig_functions() {
/**
* Add gettext __ functions to twig functions.
*/
$function = new Twig_Function('__', '__');
$this->twig->addFunction($function);
}
/**
* Load the plugin translations
*/
public function load_plugins_textdomain() {
$textdomain = 'wpse_287988';
load_plugin_textdomain( $textdomain, false, basename( dirname( __FILE__ ) ) . '/languages' );
}
/**
* Define hooks required by twig class
*/
private function define_hooks() {
add_action( 'plugins_loaded', array( $this, 'load_plugins_textdomain' ) );
}
}
// End of main class
// Initialize class
function wpse_287988_twig() {
static $plugin;
if ( isset( $plugin ) && $plugin instanceof WPSE_287988_Twig ) {
return $plugin;
}
$plugin = new WPSE_287988_Twig();
return $plugin;
}
wpse_287988_twig();
// End of class initialization
// Testing code
function wpse_287988_test_render() {
$twig = wpse_287988_twig();
echo $twig->render('template.html.twig');
die();
}
add_action('init', 'wpse_287988_test_render');
// End of testing code
```
My `template.html.twig` file:
```
{% set text = "Foo" %}
{{ __(text, 'wpse_287988') }}
```
I keep my translations in languages directory in the main directory of my plugin. My translations files are named from textdomain and locale: `wpse_287988-pl_PL.po` and `wpse_287988-pl_PL.mo`.
|
287,994 |
<p>I have added this line in the nginx configuration file</p>
<pre><code>try_files $uri $uri/ /index.php?$args;
rewrite ^([^.]*[^/])$ $1/ permanent; #adding slash
</code></pre>
<p>and the permalinks are working fine, but when adding / (please see rewrite rule how i'm adding it) NGINX gives me 404 error.</p>
<p>For example
somedomain.com/post/ThisIsPermaLink (working)
after adding slash
somedomain.com/post/ThisIsPermaLink/ (gives 404 error)</p>
<p>But all this two versions are working on Apache environment.
Apache is redirecting all requests without slashes (somedomain.com/post/ThisIsPermaLink) to somedomain.com/post/ThisIsPermaLink/</p>
<p>So i need same functionality with NGINX</p>
|
[
{
"answer_id": 287995,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 1,
"selected": false,
"text": "<p>Your home is working on SSL but some elements might not be loaded from <code>https</code> but <code>http</code> like third party images or scripts. Look in source of your home site generated by browser and search for <code>http:</code> phrase to find which elements you should fix.</p>\n"
},
{
"answer_id": 288003,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may please use this query on your database to change url from http:// to https://</p>\n\n<pre><code>UPDATE wp_options SET option_value = REPLACE(option_value, 'http://winecellar.vn/', 'https://winecellar.vn/');\nUPDATE wp_postmeta SET meta_value = REPLACE(option_value, 'http://winecellar.vn/', 'https://winecellar.vn/');\nUPDATE wp_posts SET post_content = REPLACE(option_value, 'http://winecellar.vn/', 'https://winecellar.vn/');\nUPDATE wp_posts SET post_excerpt = REPLACE(option_value, 'http://winecellar.vn/', 'https://winecellar.vn/');\nUPDATE wp_posts SET guid = REPLACE(option_value, 'http://winecellar.vn/', 'https://winecellar.vn/');\n</code></pre>\n"
},
{
"answer_id": 367176,
"author": "roguebusinessmarketing.com",
"author_id": 188537,
"author_profile": "https://wordpress.stackexchange.com/users/188537",
"pm_score": 0,
"selected": false,
"text": "<p>Go to the page that is not loading secure. Right click on your mouse, click inspect. click console and you will find the error. Mine was my logo image was not loading secure. I simply deleted it from my page and then re-uploaded the same image. Bam! fixed. Some other possible places you can locate the error is right clicking the page and view page source. ctrl \"f\" and enter http in the search bar. It will let you find any other place you may have something loading not secure.</p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/287994",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69437/"
] |
I have added this line in the nginx configuration file
```
try_files $uri $uri/ /index.php?$args;
rewrite ^([^.]*[^/])$ $1/ permanent; #adding slash
```
and the permalinks are working fine, but when adding / (please see rewrite rule how i'm adding it) NGINX gives me 404 error.
For example
somedomain.com/post/ThisIsPermaLink (working)
after adding slash
somedomain.com/post/ThisIsPermaLink/ (gives 404 error)
But all this two versions are working on Apache environment.
Apache is redirecting all requests without slashes (somedomain.com/post/ThisIsPermaLink) to somedomain.com/post/ThisIsPermaLink/
So i need same functionality with NGINX
|
Your home is working on SSL but some elements might not be loaded from `https` but `http` like third party images or scripts. Look in source of your home site generated by browser and search for `http:` phrase to find which elements you should fix.
|
288,009 |
<p>The project that I'm working on have a user login section. Once the user logged in, they should be able to see a list of orders that they made in the past which are stored in the database. The list view is done by a foreach function. In this case, the user must be able to rebook any of those past order by one click and it should send the same data back to the database as a new row or duplicate the same row with a new id. My code looks like this:</p>
<pre><code><form method="post" action="">
foreach ( $row as $row ){ ?>
<div> Previous Trip from:
<?php echo $row-> your_departing .' to : '.$row-> your_destination; ?>
<?php $depart = $row-> your_departing;
$dest = $row-> your_destination;
?>
<button type="submit" name="rebook" class="signupbtn">REBOOK</button>
</div>
<?php } ?>
</form>
if ( isset( $_POST["rebook"] ) != "" ) {
$table = $wpdb->prefix."Savedata";
$wpdb->insert(
$table,
array(
'your_destination' => $dest,
'your_departing' => $depart
)
);
}
?>
</code></pre>
<p>I wrote this code to insert the data as a new row.
Do I miss something in the code? Can anyone suggest an easy way to get this done? Any helps would be great. Thanks</p>
|
[
{
"answer_id": 288208,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 0,
"selected": false,
"text": "<p>To insert something to database you should send data with post request, get this data from request and save it. You created code which will insert last row of your loop on post request.</p>\n\n<p>You should create form for each of your previous trip and add hidden input fields to have the opportunity to get them on post request.</p>\n\n<pre><code><?php\n // Handling request and saving to database should not be in template,\n // but for the simplicity of the example I will leave it here.\n if( isset( $_POST['rebook'] ) ) {\n\n // Get value from $_POST array secure way after sanitization\n $destination = filter_input( INPUT_POST, 'destination', FILTER_SANITIZE_STRING );\n $departing = filter_input( INPUT_POST, 'departing', FILTER_SANITIZE_STRING );\n\n $table = $wpdb->prefix . \"table_name\";\n $wpdb->insert(\n $table,\n array(\n 'your_destination' => $destination,\n 'your_departing' => $departing\n )\n );\n }\n?>\n <?php $rows = array(); // Get data from database ?>\n <?php foreach ( $rows as $row ): // Iterate over data ?>\n <?php\n // Create form for each previous trip to that\n // there would be an opportunity to save each\n ?>\n <form method=\"post\" action=\"\">\n <div> Previous Trip from:\n\n <?php echo $row->your_departing .' to : '.$row->your_destination; ?>\n <?php // Create hidden fields to send 'departing' and 'destination' with $_POST data ?>\n <input type=\"hidden\" name=\"departing\" value=\"<?php esc_attr( $row->your_departing ); ?>\">\n <input type=\"hidden\" name=\"destination\" value=\"<?php esc_attr( $row->your_destination ); ?>\">\n\n <button type=\"submit\" name=\"rebook\" class=\"signupbtn\">REBOOK</button>\n\n </div>\n </form>\n<?php endforeach; ?>\n</code></pre>\n"
},
{
"answer_id": 411127,
"author": "Rajan Karmaker",
"author_id": 227322,
"author_profile": "https://wordpress.stackexchange.com/users/227322",
"pm_score": -1,
"selected": false,
"text": "<p>There is a better way to do that. It is not that your approach is wrong. But you can write code like this to insert data, passing the $format third argument to $wpdb->insert. Which will be more secure.</p>\n<pre><code> if ( empty( $row->your_departing ) || empty( $row->your_destination ) ) {\n return; // Retrun if your_departing or your_destination one of these are empty\n }\n\n $defaults = array(\n 'your_destination' => '',\n 'your_departing' => '',\n );\n\n $args = array(\n 'your_destination' => $row->your_departing;\n 'your_departing' => $row->your_destination;\n );\n\n $data = wp_parse_args( $args, $defaults );\n\n $wpdb->insert(\n $wpdb->prefix . 'Savedata',\n $data,\n array(\n '%s',\n '%s',\n )\n ); // the %s will ensure these two values should be the string\n</code></pre>\n<p>You can look into the doc <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">here</a> for more details.</p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/288009",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124648/"
] |
The project that I'm working on have a user login section. Once the user logged in, they should be able to see a list of orders that they made in the past which are stored in the database. The list view is done by a foreach function. In this case, the user must be able to rebook any of those past order by one click and it should send the same data back to the database as a new row or duplicate the same row with a new id. My code looks like this:
```
<form method="post" action="">
foreach ( $row as $row ){ ?>
<div> Previous Trip from:
<?php echo $row-> your_departing .' to : '.$row-> your_destination; ?>
<?php $depart = $row-> your_departing;
$dest = $row-> your_destination;
?>
<button type="submit" name="rebook" class="signupbtn">REBOOK</button>
</div>
<?php } ?>
</form>
if ( isset( $_POST["rebook"] ) != "" ) {
$table = $wpdb->prefix."Savedata";
$wpdb->insert(
$table,
array(
'your_destination' => $dest,
'your_departing' => $depart
)
);
}
?>
```
I wrote this code to insert the data as a new row.
Do I miss something in the code? Can anyone suggest an easy way to get this done? Any helps would be great. Thanks
|
To insert something to database you should send data with post request, get this data from request and save it. You created code which will insert last row of your loop on post request.
You should create form for each of your previous trip and add hidden input fields to have the opportunity to get them on post request.
```
<?php
// Handling request and saving to database should not be in template,
// but for the simplicity of the example I will leave it here.
if( isset( $_POST['rebook'] ) ) {
// Get value from $_POST array secure way after sanitization
$destination = filter_input( INPUT_POST, 'destination', FILTER_SANITIZE_STRING );
$departing = filter_input( INPUT_POST, 'departing', FILTER_SANITIZE_STRING );
$table = $wpdb->prefix . "table_name";
$wpdb->insert(
$table,
array(
'your_destination' => $destination,
'your_departing' => $departing
)
);
}
?>
<?php $rows = array(); // Get data from database ?>
<?php foreach ( $rows as $row ): // Iterate over data ?>
<?php
// Create form for each previous trip to that
// there would be an opportunity to save each
?>
<form method="post" action="">
<div> Previous Trip from:
<?php echo $row->your_departing .' to : '.$row->your_destination; ?>
<?php // Create hidden fields to send 'departing' and 'destination' with $_POST data ?>
<input type="hidden" name="departing" value="<?php esc_attr( $row->your_departing ); ?>">
<input type="hidden" name="destination" value="<?php esc_attr( $row->your_destination ); ?>">
<button type="submit" name="rebook" class="signupbtn">REBOOK</button>
</div>
</form>
<?php endforeach; ?>
```
|
288,020 |
<p>I've got lots of posts with the same title (home estate's properties), and i need to make url of single property -> title + ID (id part, adde automatically) after making new post.</p>
<p>And is it possible to change existing one's? (i've got lots of them already created)</p>
<p>Please help, i'm stuck</p>
|
[
{
"answer_id": 288208,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 0,
"selected": false,
"text": "<p>To insert something to database you should send data with post request, get this data from request and save it. You created code which will insert last row of your loop on post request.</p>\n\n<p>You should create form for each of your previous trip and add hidden input fields to have the opportunity to get them on post request.</p>\n\n<pre><code><?php\n // Handling request and saving to database should not be in template,\n // but for the simplicity of the example I will leave it here.\n if( isset( $_POST['rebook'] ) ) {\n\n // Get value from $_POST array secure way after sanitization\n $destination = filter_input( INPUT_POST, 'destination', FILTER_SANITIZE_STRING );\n $departing = filter_input( INPUT_POST, 'departing', FILTER_SANITIZE_STRING );\n\n $table = $wpdb->prefix . \"table_name\";\n $wpdb->insert(\n $table,\n array(\n 'your_destination' => $destination,\n 'your_departing' => $departing\n )\n );\n }\n?>\n <?php $rows = array(); // Get data from database ?>\n <?php foreach ( $rows as $row ): // Iterate over data ?>\n <?php\n // Create form for each previous trip to that\n // there would be an opportunity to save each\n ?>\n <form method=\"post\" action=\"\">\n <div> Previous Trip from:\n\n <?php echo $row->your_departing .' to : '.$row->your_destination; ?>\n <?php // Create hidden fields to send 'departing' and 'destination' with $_POST data ?>\n <input type=\"hidden\" name=\"departing\" value=\"<?php esc_attr( $row->your_departing ); ?>\">\n <input type=\"hidden\" name=\"destination\" value=\"<?php esc_attr( $row->your_destination ); ?>\">\n\n <button type=\"submit\" name=\"rebook\" class=\"signupbtn\">REBOOK</button>\n\n </div>\n </form>\n<?php endforeach; ?>\n</code></pre>\n"
},
{
"answer_id": 411127,
"author": "Rajan Karmaker",
"author_id": 227322,
"author_profile": "https://wordpress.stackexchange.com/users/227322",
"pm_score": -1,
"selected": false,
"text": "<p>There is a better way to do that. It is not that your approach is wrong. But you can write code like this to insert data, passing the $format third argument to $wpdb->insert. Which will be more secure.</p>\n<pre><code> if ( empty( $row->your_departing ) || empty( $row->your_destination ) ) {\n return; // Retrun if your_departing or your_destination one of these are empty\n }\n\n $defaults = array(\n 'your_destination' => '',\n 'your_departing' => '',\n );\n\n $args = array(\n 'your_destination' => $row->your_departing;\n 'your_departing' => $row->your_destination;\n );\n\n $data = wp_parse_args( $args, $defaults );\n\n $wpdb->insert(\n $wpdb->prefix . 'Savedata',\n $data,\n array(\n '%s',\n '%s',\n )\n ); // the %s will ensure these two values should be the string\n</code></pre>\n<p>You can look into the doc <a href=\"https://developer.wordpress.org/reference/classes/wpdb/insert/\" rel=\"nofollow noreferrer\">here</a> for more details.</p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/288020",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132898/"
] |
I've got lots of posts with the same title (home estate's properties), and i need to make url of single property -> title + ID (id part, adde automatically) after making new post.
And is it possible to change existing one's? (i've got lots of them already created)
Please help, i'm stuck
|
To insert something to database you should send data with post request, get this data from request and save it. You created code which will insert last row of your loop on post request.
You should create form for each of your previous trip and add hidden input fields to have the opportunity to get them on post request.
```
<?php
// Handling request and saving to database should not be in template,
// but for the simplicity of the example I will leave it here.
if( isset( $_POST['rebook'] ) ) {
// Get value from $_POST array secure way after sanitization
$destination = filter_input( INPUT_POST, 'destination', FILTER_SANITIZE_STRING );
$departing = filter_input( INPUT_POST, 'departing', FILTER_SANITIZE_STRING );
$table = $wpdb->prefix . "table_name";
$wpdb->insert(
$table,
array(
'your_destination' => $destination,
'your_departing' => $departing
)
);
}
?>
<?php $rows = array(); // Get data from database ?>
<?php foreach ( $rows as $row ): // Iterate over data ?>
<?php
// Create form for each previous trip to that
// there would be an opportunity to save each
?>
<form method="post" action="">
<div> Previous Trip from:
<?php echo $row->your_departing .' to : '.$row->your_destination; ?>
<?php // Create hidden fields to send 'departing' and 'destination' with $_POST data ?>
<input type="hidden" name="departing" value="<?php esc_attr( $row->your_departing ); ?>">
<input type="hidden" name="destination" value="<?php esc_attr( $row->your_destination ); ?>">
<button type="submit" name="rebook" class="signupbtn">REBOOK</button>
</div>
</form>
<?php endforeach; ?>
```
|
288,040 |
<p>You can use <a href="https://codex.wordpress.org/Function_Reference/is_admin" rel="nofollow noreferrer"><code>is_admin</code></a> to check to see if the current web page is part of WordPress' administrator interface.</p>
<p>Is there a way to see if the page being processed is the registration page?</p>
|
[
{
"answer_id": 288044,
"author": "Sean Michaud",
"author_id": 43348,
"author_profile": "https://wordpress.stackexchange.com/users/43348",
"pm_score": 2,
"selected": false,
"text": "<p>You could create your own simple function.</p>\n\n<pre><code>function is_registration_page() {\n if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {\n return true;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 288049,
"author": "signal2013",
"author_id": 132866,
"author_profile": "https://wordpress.stackexchange.com/users/132866",
"pm_score": 2,
"selected": false,
"text": "<p>How about attempting to intercept the registration page via hooks. Here's an example of how hooks can be used to add a field to the registration form (below)... Depending on your situation, you can use this (and the hook to intercept a submitted form) as a means to achieve what you're looking for.</p>\n\n<p>I added in a line: $GLOBALS['is_registration'] = TRUE;</p>\n\n<p>But note, this global variable may not be available at the point you require it. You will have to test to see.</p>\n\n<pre><code><?php\nadd_action( 'register_form', 'myplugin_add_registration_fields' );\nfunction myplugin_add_registration_fields() {\n\n $GLOBALS['is_registration'] = TRUE;\n\n //Get and set any values already sent\n $user_extra = ( isset( $_POST['user_extra'] ) ) ? $_POST['user_extra'] : '';\n?>\n <label for=\"user_extra\"><?php _e( 'Extra Field', 'myplugin_textdomain' ) ?>\n <input type=\"text\" name=\"user_extra\" id=\"user_extra\" class=\"input\" value=\"<?php echo esc_attr( stripslashes( $user_extra ) ); ?>\" size=\"25\" /></label>\n<?php\n}\n?>\n</code></pre>\n\n<p>You can read more about these action/filter hooks at:\n<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/register_form</a></p>\n"
}
] |
2017/12/07
|
[
"https://wordpress.stackexchange.com/questions/288040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122391/"
] |
You can use [`is_admin`](https://codex.wordpress.org/Function_Reference/is_admin) to check to see if the current web page is part of WordPress' administrator interface.
Is there a way to see if the page being processed is the registration page?
|
You could create your own simple function.
```
function is_registration_page() {
if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {
return true;
}
return false;
}
```
|
288,061 |
<h2>Questions</h2>
<ul>
<li>Assuming that I wanted to put all the code in a custom page like <code>page-contact.php</code> how can I structure my code so I can receive email? the code works in other PHP projects, but getting an error in a WordPress environment</li>
<li>Why am I getting an error that the page cannot be found when all i need is the code from the page to handle the form?</li>
</ul>
<hr>
<h2>Background</h2>
<p>I did read another source by <a href="https://www.sitepoint.com/handling-post-requests-the-wordpress-way/" rel="nofollow noreferrer">Sitepoint about about WordPress emails</a> but this is a tiny project and I just need this to work according to how this project is setup.</p>
<p>In another PHP project I had the form action to be send according to what is written in <code>_contactform.php</code></p>
<pre><code><form action="_contactform.php" method="post" name='submitform'>
</code></pre>
<p>it works fine there. But when I reused the code in a WordPress project I then got an error that the page did not exist as it seemed to try to direct the user to the url</p>
<pre><code>http://example.com/contact/_contactform.php
</code></pre>
<p>So rather than have the action be the <code>_contactform.php</code> I think I can just put the code in the same page but how would I wrap it, etc?</p>
<p>The php file for the form starts with this</p>
<pre><code><?php
/* Set e-mail recipient */
$orderemail = "[email protected]";
$name = check_input($_POST['name']);
$email = check_input($_POST['email']);
$address = check_input($_POST['address']);
$message = "
Hello!
Your contact form has been submitted by:
Name: $name
E-mail: $email
Address:
$address
End of message
";
/* Send the message using mail() function */
mail($orderemail, $subject, $message);
</code></pre>
|
[
{
"answer_id": 288044,
"author": "Sean Michaud",
"author_id": 43348,
"author_profile": "https://wordpress.stackexchange.com/users/43348",
"pm_score": 2,
"selected": false,
"text": "<p>You could create your own simple function.</p>\n\n<pre><code>function is_registration_page() {\n if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {\n return true;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 288049,
"author": "signal2013",
"author_id": 132866,
"author_profile": "https://wordpress.stackexchange.com/users/132866",
"pm_score": 2,
"selected": false,
"text": "<p>How about attempting to intercept the registration page via hooks. Here's an example of how hooks can be used to add a field to the registration form (below)... Depending on your situation, you can use this (and the hook to intercept a submitted form) as a means to achieve what you're looking for.</p>\n\n<p>I added in a line: $GLOBALS['is_registration'] = TRUE;</p>\n\n<p>But note, this global variable may not be available at the point you require it. You will have to test to see.</p>\n\n<pre><code><?php\nadd_action( 'register_form', 'myplugin_add_registration_fields' );\nfunction myplugin_add_registration_fields() {\n\n $GLOBALS['is_registration'] = TRUE;\n\n //Get and set any values already sent\n $user_extra = ( isset( $_POST['user_extra'] ) ) ? $_POST['user_extra'] : '';\n?>\n <label for=\"user_extra\"><?php _e( 'Extra Field', 'myplugin_textdomain' ) ?>\n <input type=\"text\" name=\"user_extra\" id=\"user_extra\" class=\"input\" value=\"<?php echo esc_attr( stripslashes( $user_extra ) ); ?>\" size=\"25\" /></label>\n<?php\n}\n?>\n</code></pre>\n\n<p>You can read more about these action/filter hooks at:\n<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/register_form</a></p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288061",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104295/"
] |
Questions
---------
* Assuming that I wanted to put all the code in a custom page like `page-contact.php` how can I structure my code so I can receive email? the code works in other PHP projects, but getting an error in a WordPress environment
* Why am I getting an error that the page cannot be found when all i need is the code from the page to handle the form?
---
Background
----------
I did read another source by [Sitepoint about about WordPress emails](https://www.sitepoint.com/handling-post-requests-the-wordpress-way/) but this is a tiny project and I just need this to work according to how this project is setup.
In another PHP project I had the form action to be send according to what is written in `_contactform.php`
```
<form action="_contactform.php" method="post" name='submitform'>
```
it works fine there. But when I reused the code in a WordPress project I then got an error that the page did not exist as it seemed to try to direct the user to the url
```
http://example.com/contact/_contactform.php
```
So rather than have the action be the `_contactform.php` I think I can just put the code in the same page but how would I wrap it, etc?
The php file for the form starts with this
```
<?php
/* Set e-mail recipient */
$orderemail = "[email protected]";
$name = check_input($_POST['name']);
$email = check_input($_POST['email']);
$address = check_input($_POST['address']);
$message = "
Hello!
Your contact form has been submitted by:
Name: $name
E-mail: $email
Address:
$address
End of message
";
/* Send the message using mail() function */
mail($orderemail, $subject, $message);
```
|
You could create your own simple function.
```
function is_registration_page() {
if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {
return true;
}
return false;
}
```
|
288,076 |
<p>Wordpress can't detect any thumbnails size, I re-generated all image but not work.</p>
<p>The plugin (Simple Image Sizes) can detected all thumbnails size settings.
<a href="https://i.stack.imgur.com/BFW9i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFW9i.png" alt="enter image description here" /></a></p>
<p>But when I want to use, it can't detect any size.
<a href="https://i.stack.imgur.com/orbhu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/orbhu.png" alt="enter image description here" /></a></p>
<p>What should i do for this?</p>
|
[
{
"answer_id": 288044,
"author": "Sean Michaud",
"author_id": 43348,
"author_profile": "https://wordpress.stackexchange.com/users/43348",
"pm_score": 2,
"selected": false,
"text": "<p>You could create your own simple function.</p>\n\n<pre><code>function is_registration_page() {\n if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {\n return true;\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 288049,
"author": "signal2013",
"author_id": 132866,
"author_profile": "https://wordpress.stackexchange.com/users/132866",
"pm_score": 2,
"selected": false,
"text": "<p>How about attempting to intercept the registration page via hooks. Here's an example of how hooks can be used to add a field to the registration form (below)... Depending on your situation, you can use this (and the hook to intercept a submitted form) as a means to achieve what you're looking for.</p>\n\n<p>I added in a line: $GLOBALS['is_registration'] = TRUE;</p>\n\n<p>But note, this global variable may not be available at the point you require it. You will have to test to see.</p>\n\n<pre><code><?php\nadd_action( 'register_form', 'myplugin_add_registration_fields' );\nfunction myplugin_add_registration_fields() {\n\n $GLOBALS['is_registration'] = TRUE;\n\n //Get and set any values already sent\n $user_extra = ( isset( $_POST['user_extra'] ) ) ? $_POST['user_extra'] : '';\n?>\n <label for=\"user_extra\"><?php _e( 'Extra Field', 'myplugin_textdomain' ) ?>\n <input type=\"text\" name=\"user_extra\" id=\"user_extra\" class=\"input\" value=\"<?php echo esc_attr( stripslashes( $user_extra ) ); ?>\" size=\"25\" /></label>\n<?php\n}\n?>\n</code></pre>\n\n<p>You can read more about these action/filter hooks at:\n<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/register_form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/register_form</a></p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132927/"
] |
Wordpress can't detect any thumbnails size, I re-generated all image but not work.
The plugin (Simple Image Sizes) can detected all thumbnails size settings.
[](https://i.stack.imgur.com/BFW9i.png)
But when I want to use, it can't detect any size.
[](https://i.stack.imgur.com/orbhu.png)
What should i do for this?
|
You could create your own simple function.
```
function is_registration_page() {
if ( $GLOBALS['pagenow'] == 'wp-login.php' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register' ) {
return true;
}
return false;
}
```
|
288,089 |
<p>HTTP header of posts on my site looks like this:</p>
<pre><code>accept-ranges:bytes
cache-control:public, max-age=0,public,public
content-encoding:gzip
content-length:5369
content-type:text/html; charset=UTF-8
date:Fri, 08 Dec 2017 07:27:40 GMT
expires:Fri, 08 Dec 2017 07:19:33 GMT
link:<https://example.com/?p=5697>; rel=shortlink
server:Apache
status:200
vary:Accept-Encoding
</code></pre>
<p>How to remove this line from HTTP header responce:</p>
<pre><code>link:<https://example.com/?p=5697>; rel=shortlink
</code></pre>
<p><em>Please, do not confuse this with <code><head> </head></code> section of HTML, I removed it from there already, I would like to remove it from HTTP header response too.</em></p>
|
[
{
"answer_id": 288093,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 5,
"selected": true,
"text": "<pre><code><?php\nadd_filter('after_setup_theme', 'remove_redundant_shortlink');\n\nfunction remove_redundant_shortlink() {\n // remove HTML meta tag\n // <link rel='shortlink' href='http://example.com/?p=25' />\n remove_action('wp_head', 'wp_shortlink_wp_head', 10);\n\n // remove HTTP header\n // Link: <https://example.com/?p=25>; rel=shortlink\n remove_action( 'template_redirect', 'wp_shortlink_header', 11);\n}\n</code></pre>\n\n<p>Tested in WordPress 4.4 and up to 4.9.1</p>\n"
},
{
"answer_id": 401417,
"author": "Kentur",
"author_id": 101501,
"author_profile": "https://wordpress.stackexchange.com/users/101501",
"pm_score": 0,
"selected": false,
"text": "<p>This still works in wordpress 5.8.3 if you put it in your themes functions.php - just remember that this file might alter at upgrade.</p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288089",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25053/"
] |
HTTP header of posts on my site looks like this:
```
accept-ranges:bytes
cache-control:public, max-age=0,public,public
content-encoding:gzip
content-length:5369
content-type:text/html; charset=UTF-8
date:Fri, 08 Dec 2017 07:27:40 GMT
expires:Fri, 08 Dec 2017 07:19:33 GMT
link:<https://example.com/?p=5697>; rel=shortlink
server:Apache
status:200
vary:Accept-Encoding
```
How to remove this line from HTTP header responce:
```
link:<https://example.com/?p=5697>; rel=shortlink
```
*Please, do not confuse this with `<head> </head>` section of HTML, I removed it from there already, I would like to remove it from HTTP header response too.*
|
```
<?php
add_filter('after_setup_theme', 'remove_redundant_shortlink');
function remove_redundant_shortlink() {
// remove HTML meta tag
// <link rel='shortlink' href='http://example.com/?p=25' />
remove_action('wp_head', 'wp_shortlink_wp_head', 10);
// remove HTTP header
// Link: <https://example.com/?p=25>; rel=shortlink
remove_action( 'template_redirect', 'wp_shortlink_header', 11);
}
```
Tested in WordPress 4.4 and up to 4.9.1
|
288,092 |
<p>I was to tried create theme options admin page (without settings API)</p>
<p>in this code I'd like to know why wp_verify_nonce return false:</p>
<pre><code>main file
<?php
add_action('admin_menu', 'awesome_page_create');
function awesome_page_create() {
$page_title = 'My Awesome Admin Page';
$menu_title = 'Awesome Admin Page';
$capability = 'edit_posts';
$menu_slug = 'awesome_page';
$function = 'my_awesome_page_display';
$icon_url = '';
$position = 24;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
}
function my_awesome_page_display() {
if (!current_user_can('manage_options')) {
wp_die('Unauthorized user');
}
if (! wp_verify_nonce( '_wp_nonce', 'wpshout_option_page_example_action' )) {
wp_die('Nonce verification failed');
}
if (isset($_POST['awesome_text'])) {
update_option('awesome_text', $_POST['awesome_text']);
$value = $_POST['awesome_text'];
}
$value = get_option('awesome_text', 'hey-ho');
include 'form-file.php';
}
$value = get_option('awesome_text');
if (FALSE === $value) {
$value = 'hey-ho';
}
form-file
<h1>My Awesome Settings Page</h1>
<form method="POST">
<label for="awesome_text">Awesome Text</label>
<input type="text" name="awesome_text" id="awesome_text" value="<?php echo $value; ?>" />
<?php echo wp_nonce_field( 'wpshout_option_page_example_action' ); ?>
<input type="submit" value="Save" class="button button-primary button-large" />
</form>
</code></pre>
|
[
{
"answer_id": 288095,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": -1,
"selected": false,
"text": "<p>I think for your <code>wp_nonce_field</code> you have to use a second parameter (the field name of your custom nonce).</p>\n\n<pre><code><?php echo wp_nonce_field( 'wpshout_option_page_example_action', 'wpshout_option_page_nonce_field' ); ?>\n</code></pre>\n\n<p>Then when you're using your <code>if</code> statement for nonce use it :</p>\n\n<pre><code>if (! wp_verify_nonce( $_POST['wpshout_option_page_nonce_field'], 'wpshout_option_page_example_action' )) {\n wp_die('Nonce verification failed');\n}\n</code></pre>\n\n<p>Try it, I think it's ok :)</p>\n"
},
{
"answer_id": 387167,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<h2>Revised code</h2>\n<pre><code>if(is_admin()) {\n add_action('admin_menu', 'awesome_page_create');\n function awesome_page_create() {\n $page_title = 'My Awesome Admin Page';\n $menu_title = 'Awesome Admin Page';\n $capability = 'edit_posts';\n $menu_slug = 'awesome_page';\n $function = 'my_awesome_page_display';\n $icon_url = '';\n $position = 24;\n add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);\n }\n function my_awesome_page_display() {\n if (!current_user_can('manage_options')) {\n wp_die('Unauthorized user');\n }\n $value = get_option('awesome_text', '');\n?>\n <h1>My Awesome Settings Page</h1>\n <form method="POST">\n <label for="awesome_text">Awesome Text</label>\n <input type="text" name="awesome_text" id="awesome_text" value="<?php echo $value; ?>" />\n <?php wp_nonce_field('wpshout_option_page_example_action', 'awesome_nonce', false); ?>\n <input type="submit" value="Save" class="button button-primary button-large" />\n </form>\n<?php\n }\n add_action('init', 'process_my_awesome_form_data');\n function process_my_awesome_form_data() {\n if(isset($_REQUEST['awesome_nonce'])) {\n if(wp_verify_nonce($_REQUEST['awesome_nonce'], 'wpshout_option_page_example_action')) {\n if (isset($_POST['awesome_text'])) {\n update_option('awesome_text', $_POST['awesome_text']);\n }\n } else {\n echo 'nonce verification failed';\n }\n }\n }\n}\n</code></pre>\n<h2>Explanation</h2>\n<p><code>if(is_admin()) {</code> is to make sure, you're creating admin menu in the right context.</p>\n<p>Instead of <code>include 'form-file.php';</code>, the form is embedded in <code>my_awesome_page_display</code> function, which makes it easier to debug. The line <code><?php echo wp_nonce_field( 'wpshout_option_page_example_action' ); ?></code> in form's definition was changed to <code><?php wp_nonce_field('wpshout_option_page_example_action', 'awsome_nonce', false); ?></code>. Your original line was outputting two identical hidden input fields for <code>nonce</code>, one, because of <code>echo</code>, and second, because the fourth parameter had default value of <code>true</code> (which means - print this line).</p>\n<p>Don't process your form's submission in <code>my_awesome_page_display</code> function. Instead, use <code>init</code> hook to add the form's submission processing function <code>process_my_awsome_form_data</code>. In that function, <code>$_REQUEST['awsome_nonce']</code> is used to retrieve the value of <code>nonce</code> for verification, <code>$_POST['awesome_text']</code> is used to retrive the value of the text input.</p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288092",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132723/"
] |
I was to tried create theme options admin page (without settings API)
in this code I'd like to know why wp\_verify\_nonce return false:
```
main file
<?php
add_action('admin_menu', 'awesome_page_create');
function awesome_page_create() {
$page_title = 'My Awesome Admin Page';
$menu_title = 'Awesome Admin Page';
$capability = 'edit_posts';
$menu_slug = 'awesome_page';
$function = 'my_awesome_page_display';
$icon_url = '';
$position = 24;
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position );
}
function my_awesome_page_display() {
if (!current_user_can('manage_options')) {
wp_die('Unauthorized user');
}
if (! wp_verify_nonce( '_wp_nonce', 'wpshout_option_page_example_action' )) {
wp_die('Nonce verification failed');
}
if (isset($_POST['awesome_text'])) {
update_option('awesome_text', $_POST['awesome_text']);
$value = $_POST['awesome_text'];
}
$value = get_option('awesome_text', 'hey-ho');
include 'form-file.php';
}
$value = get_option('awesome_text');
if (FALSE === $value) {
$value = 'hey-ho';
}
form-file
<h1>My Awesome Settings Page</h1>
<form method="POST">
<label for="awesome_text">Awesome Text</label>
<input type="text" name="awesome_text" id="awesome_text" value="<?php echo $value; ?>" />
<?php echo wp_nonce_field( 'wpshout_option_page_example_action' ); ?>
<input type="submit" value="Save" class="button button-primary button-large" />
</form>
```
|
Revised code
------------
```
if(is_admin()) {
add_action('admin_menu', 'awesome_page_create');
function awesome_page_create() {
$page_title = 'My Awesome Admin Page';
$menu_title = 'Awesome Admin Page';
$capability = 'edit_posts';
$menu_slug = 'awesome_page';
$function = 'my_awesome_page_display';
$icon_url = '';
$position = 24;
add_menu_page($page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
}
function my_awesome_page_display() {
if (!current_user_can('manage_options')) {
wp_die('Unauthorized user');
}
$value = get_option('awesome_text', '');
?>
<h1>My Awesome Settings Page</h1>
<form method="POST">
<label for="awesome_text">Awesome Text</label>
<input type="text" name="awesome_text" id="awesome_text" value="<?php echo $value; ?>" />
<?php wp_nonce_field('wpshout_option_page_example_action', 'awesome_nonce', false); ?>
<input type="submit" value="Save" class="button button-primary button-large" />
</form>
<?php
}
add_action('init', 'process_my_awesome_form_data');
function process_my_awesome_form_data() {
if(isset($_REQUEST['awesome_nonce'])) {
if(wp_verify_nonce($_REQUEST['awesome_nonce'], 'wpshout_option_page_example_action')) {
if (isset($_POST['awesome_text'])) {
update_option('awesome_text', $_POST['awesome_text']);
}
} else {
echo 'nonce verification failed';
}
}
}
}
```
Explanation
-----------
`if(is_admin()) {` is to make sure, you're creating admin menu in the right context.
Instead of `include 'form-file.php';`, the form is embedded in `my_awesome_page_display` function, which makes it easier to debug. The line `<?php echo wp_nonce_field( 'wpshout_option_page_example_action' ); ?>` in form's definition was changed to `<?php wp_nonce_field('wpshout_option_page_example_action', 'awsome_nonce', false); ?>`. Your original line was outputting two identical hidden input fields for `nonce`, one, because of `echo`, and second, because the fourth parameter had default value of `true` (which means - print this line).
Don't process your form's submission in `my_awesome_page_display` function. Instead, use `init` hook to add the form's submission processing function `process_my_awsome_form_data`. In that function, `$_REQUEST['awsome_nonce']` is used to retrieve the value of `nonce` for verification, `$_POST['awesome_text']` is used to retrive the value of the text input.
|
288,099 |
<p>I'm developing a theme that has a featured posts section before the main loop of posts. Cool and fresh, right?:) All sticky posts with a featured image in place must be displayed in that section and excluded from the main loop. Easy peasy. Doing my research, I stumbled upon a <a href="https://developer.wordpress.com/2012/05/14/querying-posts-without-query_posts/" rel="nofollow noreferrer">pretty old article</a> on the matter that I found very useful. It advocates not to use <code>query_posts</code>, which I did before, and offers a more elegant approach instead:</p>
<pre><code> /**
* Filter the home page posts, and remove any featured post ID's from it. Hooked
* onto the 'pre_get_posts' action, this changes the parameters of the query
* before it gets any posts.
*
* @global array $featured_post_id
* @param WP_Query $query
* @return WP_Query Possibly modified WP_query
*/
function itheme2_home_posts( $query = false ) {
// Bail if not home, not a query, not main query, or no featured posts
if ( ! is_home() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() || ! itheme2_featuring_posts() )
return;
// Exclude featured posts from the main query
$query->set( 'post__not_in', itheme2_featuring_posts() );
// Note the we aren't returning anything.
// 'pre_get_posts' is a byref action; we're modifying the query directly.
}
add_action( 'pre_get_posts', 'itheme2_home_posts' );
/**
* Test to see if any posts meet our conditions for featuring posts.
* Current conditions are:
*
* - sticky posts
* - with featured thumbnails
*
* We store the results of the loop in a transient, to prevent running this
* extra query on every page load. The results are an array of post ID's that
* match the result above. This gives us a quick way to loop through featured
* posts again later without needing to query additional times later.
*/
function itheme2_featuring_posts() {
if ( false === ( $featured_post_ids = get_transient( 'featured_post_ids' ) ) ) {
// Proceed only if sticky posts exist.
if ( get_option( 'sticky_posts' ) ) {
$featured_args = array(
'post__in' => get_option( 'sticky_posts' ),
'post_status' => 'publish',
'no_found_rows' => true
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
$featured_post_ids[] = $featured->post->ID;
}
}
set_transient( 'featured_post_ids', $featured_post_ids );
}
}
}
// Return the post ID's, either from the cache, or from the loop
return $featured_post_ids;
}
</code></pre>
<p>Everything works great except the transients. I can't figure out how to reset the transient if sticky_posts has been updated. Probably use the <code>updated_option</code> hook? Would appreciate any help.</p>
|
[
{
"answer_id": 288102,
"author": "Drupalizeme",
"author_id": 115005,
"author_profile": "https://wordpress.stackexchange.com/users/115005",
"pm_score": 2,
"selected": true,
"text": "<p>You can try:</p>\n\n<pre><code>add_action('update_option_sticky_posts', function( $old_value, $value ) {\n $featured_args = array(\n 'post__in' => $value,\n 'post_status' => 'publish',\n 'no_found_rows' => true\n );\n\n // The Featured Posts query.\n $featured = new WP_Query( $featured_args );\n\n // Proceed only if published posts with thumbnails exist\n if ( $featured->have_posts() ) {\n while ( $featured->have_posts() ) {\n $featured->the_post();\n if ( has_post_thumbnail( $featured->post->ID ) ) {\n $featured_post_ids[] = $featured->post->ID;\n }\n }\n\n set_transient( 'featured_post_ids', $featured_post_ids );\n }\n}, 10, 2);\n</code></pre>\n\n<p>I suppose you have the post IDs on the <code>sticky_posts</code> option that's why you are querying with that in the <code>WP_Query</code></p>\n"
},
{
"answer_id": 288104,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> class offers a parameter to include/exclude sticky posts. There's no need to store their IDs anywhere. Just create a new query, and output the sticky posts that have a featured image:</p>\n\n<pre><code>$sticky = get_option( 'sticky_posts' );\n$query = new WP_Query( array( 'p' => $sticky ) );\n</code></pre>\n\n<p>Now, you can create another loop and exclude the sticky posts:</p>\n\n<pre><code>$query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );\n</code></pre>\n\n<p>You can also set the <code>'ignore_sticky_posts' => 1</code> to ignore the sticky posts in your loop.</p>\n\n<p>That's all you need.</p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288099",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31277/"
] |
I'm developing a theme that has a featured posts section before the main loop of posts. Cool and fresh, right?:) All sticky posts with a featured image in place must be displayed in that section and excluded from the main loop. Easy peasy. Doing my research, I stumbled upon a [pretty old article](https://developer.wordpress.com/2012/05/14/querying-posts-without-query_posts/) on the matter that I found very useful. It advocates not to use `query_posts`, which I did before, and offers a more elegant approach instead:
```
/**
* Filter the home page posts, and remove any featured post ID's from it. Hooked
* onto the 'pre_get_posts' action, this changes the parameters of the query
* before it gets any posts.
*
* @global array $featured_post_id
* @param WP_Query $query
* @return WP_Query Possibly modified WP_query
*/
function itheme2_home_posts( $query = false ) {
// Bail if not home, not a query, not main query, or no featured posts
if ( ! is_home() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() || ! itheme2_featuring_posts() )
return;
// Exclude featured posts from the main query
$query->set( 'post__not_in', itheme2_featuring_posts() );
// Note the we aren't returning anything.
// 'pre_get_posts' is a byref action; we're modifying the query directly.
}
add_action( 'pre_get_posts', 'itheme2_home_posts' );
/**
* Test to see if any posts meet our conditions for featuring posts.
* Current conditions are:
*
* - sticky posts
* - with featured thumbnails
*
* We store the results of the loop in a transient, to prevent running this
* extra query on every page load. The results are an array of post ID's that
* match the result above. This gives us a quick way to loop through featured
* posts again later without needing to query additional times later.
*/
function itheme2_featuring_posts() {
if ( false === ( $featured_post_ids = get_transient( 'featured_post_ids' ) ) ) {
// Proceed only if sticky posts exist.
if ( get_option( 'sticky_posts' ) ) {
$featured_args = array(
'post__in' => get_option( 'sticky_posts' ),
'post_status' => 'publish',
'no_found_rows' => true
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
$featured_post_ids[] = $featured->post->ID;
}
}
set_transient( 'featured_post_ids', $featured_post_ids );
}
}
}
// Return the post ID's, either from the cache, or from the loop
return $featured_post_ids;
}
```
Everything works great except the transients. I can't figure out how to reset the transient if sticky\_posts has been updated. Probably use the `updated_option` hook? Would appreciate any help.
|
You can try:
```
add_action('update_option_sticky_posts', function( $old_value, $value ) {
$featured_args = array(
'post__in' => $value,
'post_status' => 'publish',
'no_found_rows' => true
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
$featured_post_ids[] = $featured->post->ID;
}
}
set_transient( 'featured_post_ids', $featured_post_ids );
}
}, 10, 2);
```
I suppose you have the post IDs on the `sticky_posts` option that's why you are querying with that in the `WP_Query`
|
288,129 |
<p>I am wondering how can I add an endpoint where I would return the ninja form plugin data. I have made a function where I am getting the data from the ninja form:</p>
<pre><code>add_action('init', function() {
function getNinjaFormData(WP_REST_Request $request) {
$id = $request->get_param('id');
$settings = ['label', 'type', 'required'];
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = [];
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$data[$key][] = $formField->get_setting($setting);
}
}
return $data;
}
});
add_action( 'rest_api_init', function () {
register_rest_route( 'ninja-forms/', '/id/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'getNinjaFormData',
));
});
</code></pre>
<p>But, this is not working, what am I doing wrong?</p>
|
[
{
"answer_id": 288154,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You need to return a WP_REST_Response object instead of an array.</p>\n\n<p>See <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/</a> and <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_response/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/classes/wp_rest_response/</a>.</p>\n"
},
{
"answer_id": 292278,
"author": "Jack Song",
"author_id": 134082,
"author_profile": "https://wordpress.stackexchange.com/users/134082",
"pm_score": 0,
"selected": false,
"text": "<p>You need to return a WP_REST_Response object. Edit your code like the following:</p>\n\n<pre><code>add_action('init', function() {\n\nfunction getNinjaFormData(WP_REST_Request $request) {\n $id = $request->get_param('id');\n $settings = ['label', 'type', 'required'];\n $formFields = Ninja_Forms()->form(1)->get_fields();\n $data = [];\n\n foreach ($formFields as $formField) {\n $key = $formField->get_setting('key');\n foreach ($settings as $setting) {\n $data[$key][] = $formField->get_setting($setting);\n }\n }\n\n return new WP_REST_Response( $data, 200 );\n }\n});\n\nadd_action( 'rest_api_init', function () {\n register_rest_route( 'ninja-forms/', '/id/(?P<id>\\d+)', array(\n 'methods' => 'GET',\n 'callback' => 'getNinjaFormData',\n ));\n});\n</code></pre>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115898/"
] |
I am wondering how can I add an endpoint where I would return the ninja form plugin data. I have made a function where I am getting the data from the ninja form:
```
add_action('init', function() {
function getNinjaFormData(WP_REST_Request $request) {
$id = $request->get_param('id');
$settings = ['label', 'type', 'required'];
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = [];
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$data[$key][] = $formField->get_setting($setting);
}
}
return $data;
}
});
add_action( 'rest_api_init', function () {
register_rest_route( 'ninja-forms/', '/id/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'getNinjaFormData',
));
});
```
But, this is not working, what am I doing wrong?
|
You need to return a WP\_REST\_Response object instead of an array.
See <https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/> and <https://developer.wordpress.org/reference/classes/wp_rest_response/>.
|
288,132 |
<p>I have this page on my website - </p>
<p>It's a custom taxonomy template for a custom post type called Directory Entries with a taxonomy called directory_entry_type which is what's being pulled in here. </p>
<p>At the moment it's just pulling in all the posts under the category "Community Directory" - This category has about 6 children categories that i'd like to pull through on this page but at the moment it's just pulling in all of the posts under community directory.</p>
<p>How can I do this?</p>
<p>This is where I've got to so far - </p>
<pre><code><div id="content" class="col-md-8">
<?php
$queried_object = get_queried_object();
$term_query = $queried_object->term_id;
$current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
query_posts( array(
'posts_per_page' => -1, // you may edit this number
'orderby' => 'title',
'order' => 'ASC',
'child_of' => $current_term->term_id,
'hierarchical' => true,
'depth' => 1,
'tax_query' => array(
array(
'field' => 'term_id',
'terms' => $term_query,
'taxonomy' => $current_term->taxonomy,
)
),
'meta_query' => array(
array(
'key' => 'is_member',
'value' => '1',
'compare' => 'LIKE'
)
)
)
);
?>
<div class="grid-vw">
<ul>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink();?>">
<figure class="effect-goliath">
<?php
$image = get_field('thumbnail');
$size = 'dir-tile'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>
<figcaption>
<h2><?php the_title();?> ></h2>
</figcaption>
</figure>
</a>
</li>
<?php endwhile;
wp_reset_query();
?> </ul>
</div>
</code></pre>
<p>Thanks for any help in advance!</p>
<p>EDIT</p>
<p>So I've solved this with this </p>
<pre><code><div class="grid-vw">
<ul>
<?php
// List posts by the terms for a custom taxonomy of any post type
$post_type = 'directory_entry';
$tax = 'directory_entry_type';
$tax_args = array(
'order' => 'ASC',
'parent' => 289
);
// get all the first level terms only
$tax_terms = get_terms( $tax, $tax_args );
if ($tax_terms) {
foreach ($tax_terms as $tax_term) { // foreach first level term
// print the parent heading
?>
<li>
<a href="<?php echo get_permalink( $tax_term->ID ); ?>">
<figure class="effect-goliath">
<?php
$image = get_field('thumbnail');
$size = 'dir-tile'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>
<figcaption>
<h2><?php echo $tax_term->name; ?> ></h2>
</figcaption>
</figure>
</a>
</li>
<?php wp_reset_query();
}
}
?>
</ul>
</code></pre>
<p> </p>
<p>That's pulling in exactly what i want, but now the permalinks aren't working, could anyone tell me what I'm doing wrong there?</p>
|
[
{
"answer_id": 288145,
"author": "Adam N",
"author_id": 78232,
"author_profile": "https://wordpress.stackexchange.com/users/78232",
"pm_score": 1,
"selected": false,
"text": "<p>To clarify, is your query only pulling posts tagged as the parent category and nothing tagged as a child category? And are you saying you'd like to have everything on this page? </p>\n\n<p>You might try changing <code>child_of</code> to <code>cat</code> and get rid of <code>depth</code>.</p>\n\n<p>But TBH you may want to try a different approach at querying; this question/answer suggests that <code>query_posts()</code> is not the best method: <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">When should you use WP_Query vs query_posts() vs get_posts()?</a></p>\n\n<p>Another approach would be to query for the IDs of the child categories of this parent and then loop through them with individual post queries - if you'd want them in six sections.</p>\n"
},
{
"answer_id": 288326,
"author": "Lucy Brown",
"author_id": 84954,
"author_profile": "https://wordpress.stackexchange.com/users/84954",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this using this</p>\n\n<pre><code><div class=\"grid-vw\">\n <ul> \n\n\n\n <?php\n // List posts by the terms for a custom taxonomy of any post type\n\n $post_type = 'directory_entry';\n $tax = 'directory_entry_type';\n $tax_args = array(\n 'order' => 'ASC',\n 'parent' => 289\n );\n // get all the first level terms only\n $tax_terms = get_terms( $tax, $tax_args );\n if ($tax_terms) {\n foreach ($tax_terms as $tax_term) { // foreach first level term\n // print the parent heading\n ?>\n\n\n\n <li>\n\n <?php echo '<a href=\"'.get_term_link($tax_term).'\">';\n\n?>\n\n <figure class=\"effect-goliath\">\n <?php \n\n $image = get_field('thumbnail');\n $size = 'dir-tile'; // (thumbnail, medium, large, full or custom size)\n\n if( $image ) {\n\n echo wp_get_attachment_image( $image, $size );\n\n }\n\n ?>\n\n <figcaption>\n <h2><?php echo $tax_term->name; ?> ></h2>\n </figcaption> \n </figure>\n\n </a>\n\n </li>\n\n\n\n <?php wp_reset_query();\n\n }\n\n }\n ?>\n\n\n </ul>\n</code></pre>\n\n<p> </p>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84954/"
] |
I have this page on my website -
It's a custom taxonomy template for a custom post type called Directory Entries with a taxonomy called directory\_entry\_type which is what's being pulled in here.
At the moment it's just pulling in all the posts under the category "Community Directory" - This category has about 6 children categories that i'd like to pull through on this page but at the moment it's just pulling in all of the posts under community directory.
How can I do this?
This is where I've got to so far -
```
<div id="content" class="col-md-8">
<?php
$queried_object = get_queried_object();
$term_query = $queried_object->term_id;
$current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
query_posts( array(
'posts_per_page' => -1, // you may edit this number
'orderby' => 'title',
'order' => 'ASC',
'child_of' => $current_term->term_id,
'hierarchical' => true,
'depth' => 1,
'tax_query' => array(
array(
'field' => 'term_id',
'terms' => $term_query,
'taxonomy' => $current_term->taxonomy,
)
),
'meta_query' => array(
array(
'key' => 'is_member',
'value' => '1',
'compare' => 'LIKE'
)
)
)
);
?>
<div class="grid-vw">
<ul>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink();?>">
<figure class="effect-goliath">
<?php
$image = get_field('thumbnail');
$size = 'dir-tile'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>
<figcaption>
<h2><?php the_title();?> ></h2>
</figcaption>
</figure>
</a>
</li>
<?php endwhile;
wp_reset_query();
?> </ul>
</div>
```
Thanks for any help in advance!
EDIT
So I've solved this with this
```
<div class="grid-vw">
<ul>
<?php
// List posts by the terms for a custom taxonomy of any post type
$post_type = 'directory_entry';
$tax = 'directory_entry_type';
$tax_args = array(
'order' => 'ASC',
'parent' => 289
);
// get all the first level terms only
$tax_terms = get_terms( $tax, $tax_args );
if ($tax_terms) {
foreach ($tax_terms as $tax_term) { // foreach first level term
// print the parent heading
?>
<li>
<a href="<?php echo get_permalink( $tax_term->ID ); ?>">
<figure class="effect-goliath">
<?php
$image = get_field('thumbnail');
$size = 'dir-tile'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>
<figcaption>
<h2><?php echo $tax_term->name; ?> ></h2>
</figcaption>
</figure>
</a>
</li>
<?php wp_reset_query();
}
}
?>
</ul>
```
That's pulling in exactly what i want, but now the permalinks aren't working, could anyone tell me what I'm doing wrong there?
|
To clarify, is your query only pulling posts tagged as the parent category and nothing tagged as a child category? And are you saying you'd like to have everything on this page?
You might try changing `child_of` to `cat` and get rid of `depth`.
But TBH you may want to try a different approach at querying; this question/answer suggests that `query_posts()` is not the best method: [When should you use WP\_Query vs query\_posts() vs get\_posts()?](https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts)
Another approach would be to query for the IDs of the child categories of this parent and then loop through them with individual post queries - if you'd want them in six sections.
|
288,147 |
<p>I would like to get a list of user_nicenames and the ID. But not all the usernames which is what i'm getting now. I understand I should use the % before and after the $name only nothing seems to be working. This is the only way to get some output I found till now;</p>
<pre><code>global $wpdb; //get access to the WordPress database object variable
//get names of all users
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "SELECT user_nicename, ID
FROM $wpdb->users
WHERE user_nicename LIKE %s
";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
</code></pre>
<p>How do I limit the output to only user_nicenames starting with, so <code>$_POST['name'] .'%'</code> in normal php code.</p>
|
[
{
"answer_id": 288149,
"author": "Sneha Agarwal",
"author_id": 129447,
"author_profile": "https://wordpress.stackexchange.com/users/129447",
"pm_score": -1,
"selected": false,
"text": "<p>Your query is right the like parameter will be</p>\n\n<pre><code>global $wpdb; //get access to the WordPress database object variable\n\n//get names of all users\n$name = $wpdb->esc_like(stripslashes($_POST['name'])).\"%\";\n$sql = \"SELECT user_nicename, ID\nFROM $wpdb->users\nWHERE user_nicename LIKE %s\n\";\n\n$sql = $wpdb->prepare($sql, $name);\n\n$results = $wpdb->get_results($sql);\n</code></pre>\n"
},
{
"answer_id": 288156,
"author": "signal2013",
"author_id": 132866,
"author_profile": "https://wordpress.stackexchange.com/users/132866",
"pm_score": 0,
"selected": false,
"text": "<p>Can you verify that $_POST['name'] is obtaining a value. I suggest echoing it out to the page for debugging (maybe in comment tags if site is live). If $_POST['name'] is empty, then all results will be returned because the query will say <code>user_nicename LIKE '%'</code></p>\n\n<p>Just as a precaution in any case, you should do a conditional check to see if $_POST['name'] is set and not empty (if you never want all results returning). If empty or null, then add optional code accordingly, like to display a message that no results were found, etc.. based on how you'd want your application to work.</p>\n\n<p>I suggest breaking up your statement to do the check.. so basically:</p>\n\n<pre><code>$name = '';\n\nif(isset($_POST['name'])){\n\n $name = stripslashes($_POST['name']);\n\n}\n\necho '<!-- name: '.$name.' -->';\n\nif($name==null || $name==''){ \n\n //TODO: like return;\n\n}else {\n\n $name = $wpdb->esc_like($name).'%';\n\n ....\n}\n</code></pre>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129735/"
] |
I would like to get a list of user\_nicenames and the ID. But not all the usernames which is what i'm getting now. I understand I should use the % before and after the $name only nothing seems to be working. This is the only way to get some output I found till now;
```
global $wpdb; //get access to the WordPress database object variable
//get names of all users
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "SELECT user_nicename, ID
FROM $wpdb->users
WHERE user_nicename LIKE %s
";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
```
How do I limit the output to only user\_nicenames starting with, so `$_POST['name'] .'%'` in normal php code.
|
Can you verify that $\_POST['name'] is obtaining a value. I suggest echoing it out to the page for debugging (maybe in comment tags if site is live). If $\_POST['name'] is empty, then all results will be returned because the query will say `user_nicename LIKE '%'`
Just as a precaution in any case, you should do a conditional check to see if $\_POST['name'] is set and not empty (if you never want all results returning). If empty or null, then add optional code accordingly, like to display a message that no results were found, etc.. based on how you'd want your application to work.
I suggest breaking up your statement to do the check.. so basically:
```
$name = '';
if(isset($_POST['name'])){
$name = stripslashes($_POST['name']);
}
echo '<!-- name: '.$name.' -->';
if($name==null || $name==''){
//TODO: like return;
}else {
$name = $wpdb->esc_like($name).'%';
....
}
```
|
288,157 |
<p>Is there a way to change the content type for <em>only</em> the password reset email?</p>
<p>I have a custom HTML template for it, and have set wp_mail_content_type to text/html and am applying the template with a filter on retrieve_password_message. That all works fine and I get an HTML email for it, but I’m having a hard time figuring out where/how to reset wp_mail_content_type since I’m not actually calling wp_mail() anywhere.</p>
<p>Any help would be greatly appreciated.</p>
<p>EDIT - here’s the code I’m using.</p>
<p>This is the function that changes the content type:</p>
<pre><code>function xxx_wp_email_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );
</code></pre>
<p>And here’s the function that changes the email itself:</p>
<pre><code>function xxx_wp_retrieve_password_message( $content, $key ) {
ob_start();
$email_subject = xxx_wp_retrieve_password_title();
include( 'templates/email_header.php' );
include( 'templates/lost_password_email.php' );
include( 'templates/email_footer.php' );
$message = ob_get_contents();
ob_end_clean();
return $message;
}
add_filter( 'retrieve_password_message', 'xxx_wp_retrieve_password_message', 10, 2 );
</code></pre>
<p>Typically I’d add a <code>remove_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );</code> after a call to <code>wp_mail()</code>, but there isn’t one here.</p>
|
[
{
"answer_id": 288159,
"author": "signal2013",
"author_id": 132866,
"author_profile": "https://wordpress.stackexchange.com/users/132866",
"pm_score": 3,
"selected": true,
"text": "<p>I suspect you implemented the hook something like this:</p>\n\n<pre><code>function wp_set_html_mail_content_type() {\n return 'text/html';\n}\nadd_filter( 'wp_mail_content_type', 'wp_set_html_mail_content_type' );\n</code></pre>\n\n<p>More info: <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type</a></p>\n\n<p>Did you need to reset the content type at a later point?</p>\n\n<hr>\n\n<p>** UPDATE: try intercept it with a global variable:</p>\n\n<pre><code>function xxx_wp_email_content_type() {\n if($GLOBALS[\"use_html_content_type\"]){\n return 'text/html';\n }else{\n return 'text/plain';\n }\n}\nadd_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );\n\nfunction xxx_wp_retrieve_password_message( $content, $key ) {\n ob_start();\n\n $GLOBALS[\"use_html_content_type\"] = TRUE;\n\n $email_subject = xxx_wp_retrieve_password_title();\n\n include( 'templates/email_header.php' );\n include( 'templates/lost_password_email.php' );\n include( 'templates/email_footer.php' );\n\n $message = ob_get_contents();\n ob_end_clean();\n\n return $message;\n}\nadd_filter( 'retrieve_password_message', 'xxx_wp_retrieve_password_message', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 302439,
"author": "squarecandy",
"author_id": 41488,
"author_profile": "https://wordpress.stackexchange.com/users/41488",
"pm_score": 0,
"selected": false,
"text": "<p>This doesn't technically answer the question - but more the question behind the question. The reason you might want to set the content type only for the password reset email is that setting all system emails to <code>text/html</code> will break the default password reset email.</p>\n\n<p>I suggest using the <code>retrieve_password_message</code> filter in combination with the <code>wp_mail_content_type</code> filter to make the password reset email compatible with the HTML format:</p>\n\n<pre><code><?php\n// adding support for html emails\n// this converts ALL wp_mail emails to HTML, which messes up the password reset\nadd_filter( 'wp_mail_content_type','squarecandy_set_content_type' );\nfunction squarecandy_set_content_type() {\n return \"text/html\";\n}\n\n// add this filter too\n// this will make the password reset email compatible with the HTML format\nadd_filter( 'retrieve_password_message', 'squarecandy_retrieve_password_message', 10, 1 );\nfunction squarecandy_retrieve_password_message( $message ) {\n // Revise the message content to make it HTML email compatible\n $message = str_replace('<','',$message);\n $message = str_replace('>','',$message);\n $message = str_replace(\"\\n\",'<br>',$message);\n // make any additional modifications to the message here...\n return $message;\n}\n</code></pre>\n\n<p>Otherwise, if you only want to set individual emails to <code>text/html</code>, the <code>$GLOBALS</code> method in the answer from @signal2013 also works, but might be better applied to target your <em>custom</em> email instead of to the default password reset email (leave this as the default <code>text/plain</code>).</p>\n"
},
{
"answer_id": 315350,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 1,
"selected": false,
"text": "<p>This way works for me without setting a <code>$GLOBAL</code>:</p>\n\n<pre><code>function xxx_wp_email_content_type() {\n return 'text/html';\n}\n\nfunction xxx_wp_retrieve_password_message( $content, $key ) {\n add_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );\n\n ob_start();\n\n $email_subject = xxx_wp_retrieve_password_title();\n\n include( 'templates/email_header.php' );\n include( 'templates/lost_password_email.php' );\n include( 'templates/email_footer.php' );\n\n $message = ob_get_contents();\n ob_end_clean();\n\n return $message;\n}\nadd_filter( 'retrieve_password_message', 'xxx_wp_retrieve_password_message', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 407408,
"author": "Gruffy",
"author_id": 52665,
"author_profile": "https://wordpress.stackexchange.com/users/52665",
"pm_score": 0,
"selected": false,
"text": "<p>Since Wordpress 6.0 you can use the <code>retrieve_password_notification_email</code> to access (among other things) the headers for <strong>only</strong> the lost password email:</p>\n<pre><code>function set_lost_password_email_content_type(array $defaults, string $key, string $user_login, WP_User $user_data): array\n{\n if (!isset($defaults['headers'])) {\n $defaults['headers'] = [];\n }\n\n $defaults['headers'] = (array) $defaults['headers'];\n\n $defaults['headers'][] = 'Content-Type: text/html';\n\n return $defaults;\n}\n\nadd_filter(\n 'retrieve_password_notification_email',\n 'set_lost_password_email_content_type',\n 10,\n 4\n);\n</code></pre>\n<p>The filter is called in <code>wp-includes/user.php</code>:</p>\n<pre><code>/**\n * Filters the contents of the reset password notification email sent to the user.\n *\n * @since 6.0.0\n *\n * @param array $defaults {\n * The default notification email arguments. Used to build wp_mail().\n *\n * @type string $to The intended recipient - user email address.\n * @type string $subject The subject of the email.\n * @type string $message The body of the email.\n * @type string $headers The headers of the email.\n * }\n * @type string $key The activation key.\n * @type string $user_login The username for the user.\n * @type WP_User $user_data WP_User object.\n */\n$notification_email = apply_filters( 'retrieve_password_notification_email', $defaults, $key, $user_login, $user_data );\n</code></pre>\n"
}
] |
2017/12/08
|
[
"https://wordpress.stackexchange.com/questions/288157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132966/"
] |
Is there a way to change the content type for *only* the password reset email?
I have a custom HTML template for it, and have set wp\_mail\_content\_type to text/html and am applying the template with a filter on retrieve\_password\_message. That all works fine and I get an HTML email for it, but I’m having a hard time figuring out where/how to reset wp\_mail\_content\_type since I’m not actually calling wp\_mail() anywhere.
Any help would be greatly appreciated.
EDIT - here’s the code I’m using.
This is the function that changes the content type:
```
function xxx_wp_email_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );
```
And here’s the function that changes the email itself:
```
function xxx_wp_retrieve_password_message( $content, $key ) {
ob_start();
$email_subject = xxx_wp_retrieve_password_title();
include( 'templates/email_header.php' );
include( 'templates/lost_password_email.php' );
include( 'templates/email_footer.php' );
$message = ob_get_contents();
ob_end_clean();
return $message;
}
add_filter( 'retrieve_password_message', 'xxx_wp_retrieve_password_message', 10, 2 );
```
Typically I’d add a `remove_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );` after a call to `wp_mail()`, but there isn’t one here.
|
I suspect you implemented the hook something like this:
```
function wp_set_html_mail_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'wp_set_html_mail_content_type' );
```
More info: <https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_mail_content_type>
Did you need to reset the content type at a later point?
---
\*\* UPDATE: try intercept it with a global variable:
```
function xxx_wp_email_content_type() {
if($GLOBALS["use_html_content_type"]){
return 'text/html';
}else{
return 'text/plain';
}
}
add_filter( 'wp_mail_content_type', 'xxx_wp_email_content_type' );
function xxx_wp_retrieve_password_message( $content, $key ) {
ob_start();
$GLOBALS["use_html_content_type"] = TRUE;
$email_subject = xxx_wp_retrieve_password_title();
include( 'templates/email_header.php' );
include( 'templates/lost_password_email.php' );
include( 'templates/email_footer.php' );
$message = ob_get_contents();
ob_end_clean();
return $message;
}
add_filter( 'retrieve_password_message', 'xxx_wp_retrieve_password_message', 10, 2 );
```
|
288,210 |
<p>I have a WordPress website and I changed some CSS with Custom CSS Plugin to adjust the position of the Footer. Here my CSS Changes:</p>
<pre><code>.page-id-736 .main-title {
visibility: visible;
display: none;
}
.page-id-1981 .main-title {
visibility: visible;
display: none;
}
.page-id-2005 .main-title {
visibility: visible;
display: none;
}
.page-id-1989 .main-title {
visibility: visible;
display: none;
}
.page-id-1992 .main-title {
visibility: visible;
display: none;
}
.page-id-1997 .main-title {
visibility: visible;
display: none;
}
.page-id-3318 .main-title {
visibility: visible;
display: none;
}
.page-id-3339 .main-title {
visibility: visible;
display: none;
}
.page-id-3345 .main-title {
visibility: visible;
display: none;
}
.page-id-3348 .main-title {
visibility: visible;
display: none;
}
.page-id-3351 .main-title {
visibility: visible;
display: none;
}
.page-id-3354 .main-title {
visibility: visible;
display: none;
}
.page-id-736 .main-title + .breadcrumbs {
display: none;
}
.page-id-1981 .main-title + .breadcrumbs {
display: none;
}
.page-id-2005 .main-title + .breadcrumbs {
display: none;
}
.page-id-1989 .main-title + .breadcrumbs {
display: none;
}
.page-id-1992 .main-title + .breadcrumbs {
display: none;
}
.page-id-1997 .main-title + .breadcrumbs {
display: none;
}
.page-id-3318 .main-title + .breadcrumbs {
display: none;
}
.page-id-3339 .main-title + .breadcrumbs {
display: none;
}
.page-id-3345 .main-title + .breadcrumbs {
display: none;
}
.page-id-3348 .main-title + .breadcrumbs {
display: none;
}
.page-id-3351 .main-title + .breadcrumbs {
display: none;
}
.page-id-3354 .main-title + .breadcrumbs {
display: none;
}
.hentry__content .page-box p {
display: none;
}
.comment {
display: none;
}
.col-xs-12.form-group {
display: none;
}
#comments.comments-post-1 {
display: none;
}
.page-id-2362 .footer {
margin: -45px;
}
.page-id-2362 .row {
text-align: center;
}
</code></pre>
<p>and this is what my homepage looks like now:
<a href="https://i.stack.imgur.com/dfGOM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dfGOM.jpg" alt="enter image description here"></a></p>
<p>Could someone please help me?
Thanks,
Nico</p>
|
[
{
"answer_id": 288216,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": 0,
"selected": false,
"text": "<p>How could it help with the power of the code in question? If you can not share the URL of your site (understandable), at least share enough code with which we can recreate the situation / problem and be able to respond accordingly.</p>\n"
},
{
"answer_id": 288242,
"author": "Ideatron",
"author_id": 132928,
"author_profile": "https://wordpress.stackexchange.com/users/132928",
"pm_score": 2,
"selected": true,
"text": "<p>The problem is your <strong>footer has a -45px margin</strong> on it. \nI think you were looking to limit this vertically.</p>\n\n<p>so it should be <strong>margin-top: -45px on your footer</strong>.</p>\n\n<p>Then you can remove the <strong>overflow-x: hidden; from your body .boxed-container{}</strong>\nwhich is why the second scroll bar is appearing ( once you have defined a scroll behavior this is your problem ) just removing the overflow-x on the body .boxed-container will solve your problem but the footer having that -45px margin is what is the root cause of all your problems.</p>\n"
}
] |
2017/12/09
|
[
"https://wordpress.stackexchange.com/questions/288210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133003/"
] |
I have a WordPress website and I changed some CSS with Custom CSS Plugin to adjust the position of the Footer. Here my CSS Changes:
```
.page-id-736 .main-title {
visibility: visible;
display: none;
}
.page-id-1981 .main-title {
visibility: visible;
display: none;
}
.page-id-2005 .main-title {
visibility: visible;
display: none;
}
.page-id-1989 .main-title {
visibility: visible;
display: none;
}
.page-id-1992 .main-title {
visibility: visible;
display: none;
}
.page-id-1997 .main-title {
visibility: visible;
display: none;
}
.page-id-3318 .main-title {
visibility: visible;
display: none;
}
.page-id-3339 .main-title {
visibility: visible;
display: none;
}
.page-id-3345 .main-title {
visibility: visible;
display: none;
}
.page-id-3348 .main-title {
visibility: visible;
display: none;
}
.page-id-3351 .main-title {
visibility: visible;
display: none;
}
.page-id-3354 .main-title {
visibility: visible;
display: none;
}
.page-id-736 .main-title + .breadcrumbs {
display: none;
}
.page-id-1981 .main-title + .breadcrumbs {
display: none;
}
.page-id-2005 .main-title + .breadcrumbs {
display: none;
}
.page-id-1989 .main-title + .breadcrumbs {
display: none;
}
.page-id-1992 .main-title + .breadcrumbs {
display: none;
}
.page-id-1997 .main-title + .breadcrumbs {
display: none;
}
.page-id-3318 .main-title + .breadcrumbs {
display: none;
}
.page-id-3339 .main-title + .breadcrumbs {
display: none;
}
.page-id-3345 .main-title + .breadcrumbs {
display: none;
}
.page-id-3348 .main-title + .breadcrumbs {
display: none;
}
.page-id-3351 .main-title + .breadcrumbs {
display: none;
}
.page-id-3354 .main-title + .breadcrumbs {
display: none;
}
.hentry__content .page-box p {
display: none;
}
.comment {
display: none;
}
.col-xs-12.form-group {
display: none;
}
#comments.comments-post-1 {
display: none;
}
.page-id-2362 .footer {
margin: -45px;
}
.page-id-2362 .row {
text-align: center;
}
```
and this is what my homepage looks like now:
[](https://i.stack.imgur.com/dfGOM.jpg)
Could someone please help me?
Thanks,
Nico
|
The problem is your **footer has a -45px margin** on it.
I think you were looking to limit this vertically.
so it should be **margin-top: -45px on your footer**.
Then you can remove the **overflow-x: hidden; from your body .boxed-container{}**
which is why the second scroll bar is appearing ( once you have defined a scroll behavior this is your problem ) just removing the overflow-x on the body .boxed-container will solve your problem but the footer having that -45px margin is what is the root cause of all your problems.
|
288,231 |
<p>What would be the best way to split custom WP_Query results into different post types? </p>
<p>I'm using multiple queries, but is it the most effective solution in performance terms? </p>
<pre><code>$results = new WP_Query(array('post_type' => 'post_type_1'));
$results2 = new WP_Query(array('post_type' => 'post_type_2'));
if have posts
...loop $results
if have posts
...loop $results2
</code></pre>
|
[
{
"answer_id": 288245,
"author": "Ben HartLenn",
"author_id": 6645,
"author_profile": "https://wordpress.stackexchange.com/users/6645",
"pm_score": 0,
"selected": false,
"text": "<p>You could try doing one query to the database for all results, then use <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\"><code>get_post_type()</code></a> to break up the results into separate loops for each post type. Depending on the content you're working with it could improve performance if the PHP operations become faster than using two database queries, you'll have to test that for yourself though.</p>\n\n<pre><code><?php\n$all_results = new WP_Query([\n 'post_type' => ['post_type_1', 'post_type_2'] \n]);\n\n// initiate counter variables\n$count_post_type_1s = 0;\n$count_post_type_2s = 0;\n\nwhile ( $all_results->have_posts() ) : $all_results->the_post();\n if( get_post_type($post) == 'post_type_1' ) {\n // increment counter variable for post type 1 being found\n $count_post_type_1s++;\n // post_type_1 output\n the_title();\n }\nendwhile;\n// check if counter variable is still 0, if it is no post type 1's were found\nif( $count_post_type_1s == 0 ) {\n echo \"No post type 1's have been found\";\n}\n\n // Rewind posts to use same query again\n$all_results->rewind_posts();\n\n// do some stuff in between loops\n\nwhile ( $all_results->have_posts() ) : $all_results->the_post();\n // increment counter variable for post type 2 being found\n $count_post_type_2s++;\n if( get_post_type($post) == 'post_type_2' ) {\n // post_type_2 output\n the_title();\n }\nendwhile;\n// check if counter variable is still 0, if it is no post type 2's were found\nif( $count_post_type_2s == 0 ) {\n echo \"No post type 2's have been found\";\n}\n</code></pre>\n"
},
{
"answer_id": 288261,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>There is no need to split the query or do multiple queries. Just use the parameter <code>orderby</code> with value <code>post_type</code> to sort separated by post types. You can use a second value for additional sorting, e.g. by <code>date</code>. See <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">Codex: Class Reference | WP_Query | Order & Orderby Parameters </a> for more information.</p>\n"
}
] |
2017/12/09
|
[
"https://wordpress.stackexchange.com/questions/288231",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] |
What would be the best way to split custom WP\_Query results into different post types?
I'm using multiple queries, but is it the most effective solution in performance terms?
```
$results = new WP_Query(array('post_type' => 'post_type_1'));
$results2 = new WP_Query(array('post_type' => 'post_type_2'));
if have posts
...loop $results
if have posts
...loop $results2
```
|
There is no need to split the query or do multiple queries. Just use the parameter `orderby` with value `post_type` to sort separated by post types. You can use a second value for additional sorting, e.g. by `date`. See [Codex: Class Reference | WP\_Query | Order & Orderby Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) for more information.
|
288,250 |
<p>My draft posts will have custom field which contains value as email address. So whenever I publish the post, it will send email to the user. It's working fine. However, if I updates the post, it still sends the email again and again. Here is my piece of code:</p>
<pre><code>add_action( 'save_post', 'send_email' );
function send_email( $post_id ) {
if ( !wp_is_post_revision( $post_id ) ) {
$post_url = get_permalink( $post_id );
$subject = 'Your post is published!';
$message = "Testing!";
$message .= "<a href='". $post_url. "'>Click here to view</a>";
$custom_field_name = 'author_email';
$email = get_post_meta($post_id, $custom_field_name, true);
wp_mail($email, $subject, $message );
}
}
</code></pre>
<p>I researched the topic and here is the solution I found here in this <a href="https://stackoverflow.com/questions/20384299/send-mail-after-publish-post-on-wordpress">link</a> but how do I update in my code. Any help will be appreciated!</p>
|
[
{
"answer_id": 288251,
"author": "Por",
"author_id": 31832,
"author_profile": "https://wordpress.stackexchange.com/users/31832",
"pm_score": 0,
"selected": false,
"text": "<pre><code>add_action( 'save_post', 'send_email' );\nfunction send_email( $post_id ) {\n\n if ( !wp_is_post_revision( $post_id ) && ( get_post_status($post_id) !== 'publish') ) {\n $post_url = get_permalink( $post_id );\n $subject = 'Your post is published!';\n $message = \"Testing!\";\n $message .= \"<a href='\". $post_url. \"'>Click here to view</a>\";\n $custom_field_name = 'author_email';\n $email = get_post_meta($post_id, $custom_field_name, true); \n wp_mail($email, $subject, $message ); \n }\n}\n</code></pre>\n\n<p>We could check by get_post_status functions, not to send email again.</p>\n"
},
{
"answer_id": 288253,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 2,
"selected": false,
"text": "<p>Try to use <code>publish_post</code> hook instead of <code>save_post</code> : <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post</a> : \"<code>publish_post</code> is an action triggered whenever a post is published, or if it is edited and the status is changed to publish.\"</p>\n\n<p><strong>Updated response</strong> : let's give a try with post status transition, to be sure it's only when the post goes to publish status. <a href=\"https://codex.wordpress.org/Post_Status_Transitions\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Post_Status_Transitions</a></p>\n\n<pre><code>function send_email( $new_status, $old_status, $post) {\n if ( $new_status != $old_status && $new_status == \"publish\") {\n $post_url = get_permalink( $post->ID );\n $subject = 'Your post is published!';\n $message = \"Testing!\";\n $message .= \"<a href='\". $post_url. \"'>Click here to view</a>\";\n $custom_field_name = 'author_email';\n $email = get_post_meta($post->ID, $custom_field_name, true); \n wp_mail($email, $subject, $message ); \n }\n}\nadd_action( 'transition_post_status', 'send_email', 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 288254,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 2,
"selected": true,
"text": "<p>You need to use <a href=\"https://codex.wordpress.org/Post_Status_Transitions#.7Bold_status.7D_to_.7Bnew_status.7D_Hook\" rel=\"nofollow noreferrer\">{old_status}<em>to</em>{new_status} hook</a>. And use <code>draft</code> and <code>publish</code> statuses. This hook will only be executed when your post will change status from <code>draft</code> to <code>publish</code>.</p>\n\n<pre><code>function wpse_288250_send_email( $post ) {\n\n $post_id = $post->ID;\n\n if( wp_is_post_revision( $post_id ) ) {\n return;\n }\n\n $post_url = get_permalink( $post_id );\n $subject = 'Your post is published!';\n\n $message = \"Testing!\";\n $message .= \"<a href='\". $post_url. \"'>Click here to view</a>\";\n\n $email = get_post_meta($post_id, 'author_email', true ); \n\n wp_mail($email, $subject, $message );\n}\n\nadd_action( 'draft_to_publish', 'wpse_288250_send_email' );\n</code></pre>\n\n<p>Keep in mind if you change your post status back to <code>draft</code> and again to <code>publish</code> e-mail will be send again. To prevent this you can update post meta which will tell you if e-mail was already sent.</p>\n\n<pre><code>function wpse_288250_send_email_once( $post ) {\n\n $post_id = $post->ID;\n\n if( wp_is_post_revision( $post_id ) ) {\n return;\n }\n\n $email_sent = get_post_meta( $post_id, 'email_sent' );\n\n if( $email_sent ) {\n return;\n }\n\n $post_url = get_permalink( $post_id );\n $subject = 'Your post is published!';\n\n $message = \"Testing!\";\n $message .= \"<a href='\". $post_url. \"'>Click here to view</a>\";\n\n $email = get_post_meta($post_id, 'author_email', true ); \n\n wp_mail($email, $subject, $message );\n update_post_meta( $post_id, 'email_sent', true );\n}\n\nadd_action( 'draft_to_publish', 'wpse_288250_send_email_once' );\n</code></pre>\n"
}
] |
2017/12/10
|
[
"https://wordpress.stackexchange.com/questions/288250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36797/"
] |
My draft posts will have custom field which contains value as email address. So whenever I publish the post, it will send email to the user. It's working fine. However, if I updates the post, it still sends the email again and again. Here is my piece of code:
```
add_action( 'save_post', 'send_email' );
function send_email( $post_id ) {
if ( !wp_is_post_revision( $post_id ) ) {
$post_url = get_permalink( $post_id );
$subject = 'Your post is published!';
$message = "Testing!";
$message .= "<a href='". $post_url. "'>Click here to view</a>";
$custom_field_name = 'author_email';
$email = get_post_meta($post_id, $custom_field_name, true);
wp_mail($email, $subject, $message );
}
}
```
I researched the topic and here is the solution I found here in this [link](https://stackoverflow.com/questions/20384299/send-mail-after-publish-post-on-wordpress) but how do I update in my code. Any help will be appreciated!
|
You need to use [{old\_status}*to*{new\_status} hook](https://codex.wordpress.org/Post_Status_Transitions#.7Bold_status.7D_to_.7Bnew_status.7D_Hook). And use `draft` and `publish` statuses. This hook will only be executed when your post will change status from `draft` to `publish`.
```
function wpse_288250_send_email( $post ) {
$post_id = $post->ID;
if( wp_is_post_revision( $post_id ) ) {
return;
}
$post_url = get_permalink( $post_id );
$subject = 'Your post is published!';
$message = "Testing!";
$message .= "<a href='". $post_url. "'>Click here to view</a>";
$email = get_post_meta($post_id, 'author_email', true );
wp_mail($email, $subject, $message );
}
add_action( 'draft_to_publish', 'wpse_288250_send_email' );
```
Keep in mind if you change your post status back to `draft` and again to `publish` e-mail will be send again. To prevent this you can update post meta which will tell you if e-mail was already sent.
```
function wpse_288250_send_email_once( $post ) {
$post_id = $post->ID;
if( wp_is_post_revision( $post_id ) ) {
return;
}
$email_sent = get_post_meta( $post_id, 'email_sent' );
if( $email_sent ) {
return;
}
$post_url = get_permalink( $post_id );
$subject = 'Your post is published!';
$message = "Testing!";
$message .= "<a href='". $post_url. "'>Click here to view</a>";
$email = get_post_meta($post_id, 'author_email', true );
wp_mail($email, $subject, $message );
update_post_meta( $post_id, 'email_sent', true );
}
add_action( 'draft_to_publish', 'wpse_288250_send_email_once' );
```
|
288,280 |
<p>I am using Time.ly's All-In-One Event Calendar plugin. I am trying to get a value from the wp_ai1ec_event table in the column entitled "end". I want to get this based on the post_id. Since this is a custom table it's post_id is the same as the post table's. I have tried everything I can think of to get this value. Been working on it for days, trying all the results I get from Google searches. Nothing seems to work. I've tried:</p>
<blockquote>
<p>$event_date = get_post_meta($HitID, 'end', true);</p>
</blockquote>
<p>and </p>
<blockquote>
<p>$event_date = mysql_query("SELECT end FROM wp_ai1ec_event WHERE
post_id = '".$HitID."'");</p>
</blockquote>
<p>Among many other things. These seemed to be the closest.</p>
<p>Nothing I have tried works. I simply do not have enough self-taught PHP ability to get this working. Any help would be appreciated.</p>
<p>The goal is to get the value in the table column "end" of the table "wp_ai1ec_event" based on the post_id, in this case $HitID.</p>
|
[
{
"answer_id": 288343,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 2,
"selected": true,
"text": "<p>These bigger plugins are often \"too cool\" to use post_meta/post_custom - thats why you were unable to retrieve the data via the normal plugin way of storing additional info. The dev documentation for ai1ec in bleak, I couldn't find any functions to simplify the task you were after (though they do exist in the source code if browsed long enough).</p>\n\n<p>The table you're after is <code>wp_ai1ec_events</code> (plural. not <code>wp_ai1ec_event</code>).</p>\n\n<p>Using a tool like phpmyadmin is a great way to build your queries before hand, then make the work in your php code.</p>\n\n<p>I was able to retrieve the <code>end</code> date information with the following:</p>\n\n<pre><code>add_action('init','myplugin_get_alic_enddate');\nfunction myplugin_get_alic_enddate() {\n global $wpdb;\n\n $HitID = 537; // wtv\n $query = \"SELECT end FROM `{$wpdb->prefix}ai1ec_events` WHERE `post_id` = {$HitID}\";\n $event = $wpdb->get_row($query); \n\n //echo $event->end;\n //echo date(get_option('date_format'),$event->end);\n}\n</code></pre>\n\n<p>This does nothing with events that are all day events or ones with no end date set (obviously).</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>To reflect the code posted by OP in another answer</p>\n\n<pre><code>add_filter('relevanssi_hits_filter', 'rlv_remove_expired');\n\nfunction rlv_remove_expired($hits) {\n global $wpdb;\n\n $non_expired = array();\n $now = time();\n\n foreach ($hits[0] as $hit) {\n\n $HitID = $hit->ID;\n $Result_PostType = get_post_type($HitID);\n\n if( $Result_PostType == 'ai1ec_event' ){\n\n echo \"<pre>Made it to: if(Result_PostType=='ai1ec_event')</pre>\";\n\n $query = \"SELECT end FROM {$wpdb->prefix}ai1ec_events WHERE post_id = {$HitID}\";\n $row = $wpdb->get_row($query); \n\n if($wpdb->last_error !== '') {\n echo \"<pre> MYSQL ERROR:\\n\";\n $wpdb->print_error();\n echo \"</pre>\";\n }\n\n $end_date = $row->end;\n\n echo \"<pre>In Function.\\n End Date: \".$end_date.\"\\n HitID: \".$HitID.\"</pre>\";\n\n if($end_date >= $now)\n $non_expired[] = $hit;\n\n } else {\n $end_date = 0;\n $non_expired[] = $hit;\n }\n\n echo \"<pre>Hit ID: \".$HitID.\"\\n End Date: \".$end_date.\"\\n Now: \".$now.\"\\n Post Type: \".$Result_PostType.\"</pre>\";\n } // end foreach\n\n $hits[0] = $non_expired;\n return $hits;\n}\n</code></pre>\n"
},
{
"answer_id": 288354,
"author": "Kirk",
"author_id": 110216,
"author_profile": "https://wordpress.stackexchange.com/users/110216",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for this. Much further than I have gotten.\nHere is my complete filter code. This code is to make it so that only non-expired events show in search. I have put your code, David Sword, in but needed to comment out some of it to get to run. Also, in your code (or how it was marked as code by the stackexchange) you have the \" ' \" as \" ` \" which generated an error so I changed them to normal single quote.</p>\n\n<pre><code> add_filter('relevanssi_hits_filter', 'rlv_remove_expired');function rlv_remove_expired($hits) {\n$non_expired = array();\n$now = time();\nforeach ($hits[0] as $hit) {\n $HitID=$hit->ID;\n $Result_PostType=get_post_type($HitID);\n if($Result_PostType=='ai1ec_event'){\n echo \"<strong>Made it to: if(Result_PostType=='ai1ec_event')</strong><br>\";\n\n //add_action('init','myplugin_get_alic_enddate');\n //function myplugin_get_alic_enddate() {\n global $wpdb;\n $query = \"SELECT end FROM '{$wpdb->prefix}ai1ec_events' WHERE 'post_id' = {$HitID}\";\n $end_date = $wpdb->get_row($query); \n echo \"<strong>In Function.<br>End Date: \".$end_date.\"<br>HitID: \".$HitID.\"</strong><br>\";\n //}\n if($end_date >= $now){\n $non_expired[] = $hit;\n }\n }else{\n $end_date = 0;\n $non_expired[] = $hit;\n }\n echo \"<p>Hit ID: \".$HitID.\"<br>End Date: \".$end_date.\"<br>Now: \".$now.\"<br>Post Type: \".$Result_PostType.\"</p>\";\n }\n $hits[0] = $non_expired;\n return $hits;\n }\n</code></pre>\n"
}
] |
2017/12/10
|
[
"https://wordpress.stackexchange.com/questions/288280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110216/"
] |
I am using Time.ly's All-In-One Event Calendar plugin. I am trying to get a value from the wp\_ai1ec\_event table in the column entitled "end". I want to get this based on the post\_id. Since this is a custom table it's post\_id is the same as the post table's. I have tried everything I can think of to get this value. Been working on it for days, trying all the results I get from Google searches. Nothing seems to work. I've tried:
>
> $event\_date = get\_post\_meta($HitID, 'end', true);
>
>
>
and
>
> $event\_date = mysql\_query("SELECT end FROM wp\_ai1ec\_event WHERE
> post\_id = '".$HitID."'");
>
>
>
Among many other things. These seemed to be the closest.
Nothing I have tried works. I simply do not have enough self-taught PHP ability to get this working. Any help would be appreciated.
The goal is to get the value in the table column "end" of the table "wp\_ai1ec\_event" based on the post\_id, in this case $HitID.
|
These bigger plugins are often "too cool" to use post\_meta/post\_custom - thats why you were unable to retrieve the data via the normal plugin way of storing additional info. The dev documentation for ai1ec in bleak, I couldn't find any functions to simplify the task you were after (though they do exist in the source code if browsed long enough).
The table you're after is `wp_ai1ec_events` (plural. not `wp_ai1ec_event`).
Using a tool like phpmyadmin is a great way to build your queries before hand, then make the work in your php code.
I was able to retrieve the `end` date information with the following:
```
add_action('init','myplugin_get_alic_enddate');
function myplugin_get_alic_enddate() {
global $wpdb;
$HitID = 537; // wtv
$query = "SELECT end FROM `{$wpdb->prefix}ai1ec_events` WHERE `post_id` = {$HitID}";
$event = $wpdb->get_row($query);
//echo $event->end;
//echo date(get_option('date_format'),$event->end);
}
```
This does nothing with events that are all day events or ones with no end date set (obviously).
**UPDATE**
To reflect the code posted by OP in another answer
```
add_filter('relevanssi_hits_filter', 'rlv_remove_expired');
function rlv_remove_expired($hits) {
global $wpdb;
$non_expired = array();
$now = time();
foreach ($hits[0] as $hit) {
$HitID = $hit->ID;
$Result_PostType = get_post_type($HitID);
if( $Result_PostType == 'ai1ec_event' ){
echo "<pre>Made it to: if(Result_PostType=='ai1ec_event')</pre>";
$query = "SELECT end FROM {$wpdb->prefix}ai1ec_events WHERE post_id = {$HitID}";
$row = $wpdb->get_row($query);
if($wpdb->last_error !== '') {
echo "<pre> MYSQL ERROR:\n";
$wpdb->print_error();
echo "</pre>";
}
$end_date = $row->end;
echo "<pre>In Function.\n End Date: ".$end_date."\n HitID: ".$HitID."</pre>";
if($end_date >= $now)
$non_expired[] = $hit;
} else {
$end_date = 0;
$non_expired[] = $hit;
}
echo "<pre>Hit ID: ".$HitID."\n End Date: ".$end_date."\n Now: ".$now."\n Post Type: ".$Result_PostType."</pre>";
} // end foreach
$hits[0] = $non_expired;
return $hits;
}
```
|
288,296 |
<p>I’m getting overrun with these on my production site:</p>
<pre><code>PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3728
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3730
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3732
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3863
</code></pre>
<p>The above lines are in the <code>is_page()</code> and <code>is_singular()</code> functions.</p>
<p>I have no idea where these functions are being used incorrectly. What's frustrating is I can’t reproduce these on my staging site (same server as production) or on my localhost. And I can’t easily deactivate all plugins or switch themes because we have hundreds of signed in users and thousands of non-signed in users at any given time.</p>
<p>I have searched my repository for instances of <code>is_page()</code> and <code>is_singular()</code> and tried to verify that they are being called correctly. Clearly I have failed.</p>
<p>How do I figure out what's tripping these PHP Notices?</p>
<p>For the record, I browsed through the "similar questions" that popped up, before I submitted my question!</p>
|
[
{
"answer_id": 288402,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 1,
"selected": false,
"text": "<p>Stage and Prod may be on the same server but are they configured for the same version of PHP?</p>\n\n<p>A Wordpress debug plugin <em>might</em> provide you with additional info. Query Monitor <a href=\"https://en-gb.wordpress.org/plugins/query-monitor/#description\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/query-monitor/#description</a> provides a call stack for PHP Notices and Errors. After activation: as Admin User, go to an offending page. Not obvious, but the ribbon at the top should display seconds and KB, hover over this and click errors (I think). On my site (only a notice - no errors):</p>\n\n<p><a href=\"https://i.stack.imgur.com/GmSQQ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GmSQQ.jpg\" alt=\"Query Monitor ribbon\"></a></p>\n\n<p>Once you click Errors, details will be displayed including a call stack which <em>might</em> help.</p>\n\n<p>If PHP 7 is an issue - there is a compatibility checker somewhere in the WP Plugin directory which might be useful. It does give false positives e.g. a plugin may be marked incompatible even if it only uses a depracated function after checking PHP 7 is not being used by server.</p>\n"
},
{
"answer_id": 288408,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>You can create your own custom error handler and add stack trace to your error log.</p>\n\n<pre><code>set_error_handler('wpse_288408_handle_error');\n\nfunction wpse_288408_handle_error( $errno, $errstr, $errfile, $errline ) {\n\n if( $errno === E_USER_NOTICE ) {\n\n $message = 'You have an error notice: \"%s\" in file \"%s\" at line: \"%s\".' ;\n $message = sprintf($message, $errstr, $errfile, $errline);\n\n error_log($message);\n error_log(wpse_288408_generate_stack_trace());\n }\n}\n// Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238\nfunction wpse_288408_generate_stack_trace() {\n\n $e = new \\Exception();\n\n $trace = explode( \"\\n\" , $e->getTraceAsString() );\n\n // reverse array to make steps line up chronologically\n\n $trace = array_reverse($trace);\n\n array_shift($trace); // remove {main}\n array_pop($trace); // remove call to this method\n\n $length = count($trace);\n $result = array();\n\n for ($i = 0; $i < $length; $i++) {\n $result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering\n }\n\n $result = implode(\"\\n\", $result);\n $result = \"\\n\" . $result . \"\\n\";\n\n return $result;\n}\n</code></pre>\n\n<p>You can check if this is working by adding <code>trigger_error</code> somewhere in your code.</p>\n\n<pre><code>trigger_error('Annoying notice');\n</code></pre>\n\n<p>Your error log should output something like that:</p>\n\n<pre><code>2017/01/02 12:00:00 [error] 999#999: *999 FastCGI sent in stderr: \"PHP message: You have an error notice: \"Annoying notice\" in file \"/var/www/test/wp-content/plugins/test/test.php\" at line: \"99\".\nPHP message:\n1) /var/www/test/index.php(17): require('/var/www/test/w...')\n2) /var/www/test/wp-blog-header.php(13): require_once('/var/www/test/w...')\n3) /var/www/test/wp-load.php(37): require_once('/var/www/test/w...')\n4) /var/www/test/wp-config.php(93): require_once('/var/www/test/w...')\n5) /var/www/test/wp-settings.php(305): include_once('/var/www/test/w...')\n6) /var/www/test/wp-content/plugins/test/test.php(99): trigger_error('Annoying notice')\n7) [internal function]: wpse_288408_handle_error(1024, 'Annoying notice', '/var/www/test/w...', 99, Array)\" while reading response header from upstream, client: 192.168.33.1, server: test.dev, request: \"GET / HTTP/1.1\", upstream: \"fastcgi://127.0.0.1:9070\", host: \"test.dev\"\n</code></pre>\n\n<p>With this kind of message it will be much easier to find out where the problem is.</p>\n"
}
] |
2017/12/11
|
[
"https://wordpress.stackexchange.com/questions/288296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133063/"
] |
I’m getting overrun with these on my production site:
```
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3728
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3730
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3732
PHP Notice: Trying to get property of non-object in /public_html/wp-includes/class-wp-query.php on line 3863
```
The above lines are in the `is_page()` and `is_singular()` functions.
I have no idea where these functions are being used incorrectly. What's frustrating is I can’t reproduce these on my staging site (same server as production) or on my localhost. And I can’t easily deactivate all plugins or switch themes because we have hundreds of signed in users and thousands of non-signed in users at any given time.
I have searched my repository for instances of `is_page()` and `is_singular()` and tried to verify that they are being called correctly. Clearly I have failed.
How do I figure out what's tripping these PHP Notices?
For the record, I browsed through the "similar questions" that popped up, before I submitted my question!
|
You can create your own custom error handler and add stack trace to your error log.
```
set_error_handler('wpse_288408_handle_error');
function wpse_288408_handle_error( $errno, $errstr, $errfile, $errline ) {
if( $errno === E_USER_NOTICE ) {
$message = 'You have an error notice: "%s" in file "%s" at line: "%s".' ;
$message = sprintf($message, $errstr, $errfile, $errline);
error_log($message);
error_log(wpse_288408_generate_stack_trace());
}
}
// Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238
function wpse_288408_generate_stack_trace() {
$e = new \Exception();
$trace = explode( "\n" , $e->getTraceAsString() );
// reverse array to make steps line up chronologically
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
for ($i = 0; $i < $length; $i++) {
$result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
}
$result = implode("\n", $result);
$result = "\n" . $result . "\n";
return $result;
}
```
You can check if this is working by adding `trigger_error` somewhere in your code.
```
trigger_error('Annoying notice');
```
Your error log should output something like that:
```
2017/01/02 12:00:00 [error] 999#999: *999 FastCGI sent in stderr: "PHP message: You have an error notice: "Annoying notice" in file "/var/www/test/wp-content/plugins/test/test.php" at line: "99".
PHP message:
1) /var/www/test/index.php(17): require('/var/www/test/w...')
2) /var/www/test/wp-blog-header.php(13): require_once('/var/www/test/w...')
3) /var/www/test/wp-load.php(37): require_once('/var/www/test/w...')
4) /var/www/test/wp-config.php(93): require_once('/var/www/test/w...')
5) /var/www/test/wp-settings.php(305): include_once('/var/www/test/w...')
6) /var/www/test/wp-content/plugins/test/test.php(99): trigger_error('Annoying notice')
7) [internal function]: wpse_288408_handle_error(1024, 'Annoying notice', '/var/www/test/w...', 99, Array)" while reading response header from upstream, client: 192.168.33.1, server: test.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9070", host: "test.dev"
```
With this kind of message it will be much easier to find out where the problem is.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.